Home > Blockchain >  can't multiply by negative one in bash
can't multiply by negative one in bash

Time:09-21

I have this code:

#!/bin/bash
turn=1

swap_turn() {
    turn=$((expr $turn \* -1))
}

echo $turn

swap_turn

the output is:

1
./program.sh: line 5: expr 1 \* -1: syntax error in expression (error token is "1 \* -1")

and I can't figure out the problem. why can't it multiply 1 by -1?

CodePudding user response:

You are incorrectly combining $(expr ...) (command substitution) and $((...)) (arithmetic substitution); it's one

turn=$(expr $turn \* -1)

or (preferably) the other

turn=$(( turn * -1 ))

CodePudding user response:

This works for me:

#!/bin/bash
turn=1

swap_turn() {
    turn=$(( $turn * -1))
}

echo $turn

swap_turn
echo $turn
  • Related