1252748
1252748

Reputation: 15372

Bash script increments variable, but throws error

I'm trying to process some files in increments of 50. It seems to work, but I'm getting an error that the command isn't found.

File sleepTest.sh:

#!/bash/bin

id=100

for i in {1..5}; do
    $((id+=50))

    sh argTest.sh "$id"
    sleep 2

done

File argTest.sh:

#/bash/bin

id=$1
echo "processing $id..."

The output is

sleepTest.sh: line 6: 150: command not found
processing 150
sleepTest.sh: line 6: 200: command not found
processing 200
sleepTest.sh: line 6: 250: command not found
processing 250
sleepTest.sh: line 6: 300: command not found
processing 300
sleepTest.sh: line 6: 350: command not found
processing 350

So it clearly has an issue with how I'm incrementing $id, but it is still doing it. Why? And how can I increment $id. I tried simply $id+=50, but that did not work at all.

Upvotes: 2

Views: 525

Answers (2)

chepner
chepner

Reputation: 531165

Such assignments are legal inside arithmetic expressions. However, bash still tries to interpret the result of the expression as the name of a command. Either pass it as an argument to the : command (the POSIX way)

: $((id+=50))

or use a bash arithmetic statement instead of an arithmetic expression

((id+=50))

Upvotes: 3

John Kugelman
John Kugelman

Reputation: 361605

Leave out the $.

((id+=50))

((...)) performs arithmetic. $((...)) performs arithmetic and captures the result as a string. That would be fine if you did echo $((...)), but if you write just $((...)) then the shell treats that number as the name of a command to execute.

var=$((21 + 21))     # var=42
echo $((21 + 21))    # echo 42
$((21 + 21))         # execute the command `42`

Upvotes: 4

Related Questions