Kaio
Kaio

Reputation: 230

Bash interpreting increment operation as command

I'm trying to batch modify some images using a bash script, and to print out the progress. It looks to me like bash is interpreting the increment to counter as a command and is giving the following error:

augment_data.sh: line 20: 0: command not found

Here is the code:

for file in *.jpg
do
    convert $file -rotate 90 rotated_"$file"
    ((counter++))
    if $((counter % 10 == 0)); then
            echo "Rotated $counter files out of $num_files"
    fi
done

with line 20 being the one with the counter increment operation.

How can I fix this so that I don't get the error message?

Upvotes: 2

Views: 71

Answers (1)

Charles Duffy
Charles Duffy

Reputation: 295278

In an arithmetic substitution, the result of an arithmetic operation is substituted in the position of the operation itself.

In this case, $(( 1 == 0 )) has an arithmetic result of 0, and $(( 1 == 1 )) has a result of 1.

Thus, if you use $(( ... )), then this 0 or 1 is substituted in that position, and so gets run as a command. Since you don't have commands named 0 or 1 (probably), either of these will result in a command not found error.

If you use (( ... )), then the arithmetic result directly sets return value, but no expansion takes place.

Upvotes: 2

Related Questions