EXIT_FAILURE
EXIT_FAILURE

Reputation: 288

subtraction in bash doesn't work

I have the following problem with a bash script:

validParameters=0
argumentLength=${#1}
argumentLength==$((argumentLength - 1))

#[code to increment validParameters]

if [[ $validParameters != argumentLength ]]
    then
        diff=$((argumentLength - validParameters))
        printf "Attention:\n$diff invalid argument(s) found!\n"
fi
    exit 1

The error happens in the line: diff=$((argumentLength - validParameters))

=3: syntax error: operand expected (error token is "=3")

with the command script.sh abc

If I set diff to a fixed value (e.g. diff=1) instead of the subtraction, the script works perfectly.

Is my subtraction syntax somehow wrong?

Upvotes: 0

Views: 779

Answers (2)

Socowi
Socowi

Reputation: 27245

Sounds like one of the variables argumentLength and validParameters did not store a number, but something including the string =3.

For debugging, try to print both variables before subtracting them.

By the way, you can write ((diff = argumentLength - validParameters)).

Edit after your edit: Found the Bug
There is one = too much in

argumentLength==$((argumentLength - 1))

write

argumentLength=$((argumentLength - 1))

or

(( argumentLength-- ))

instead.

Upvotes: 0

John Kugelman
John Kugelman

Reputation: 361849

argumentLength==$((argumentLength - 1))

You've got two =s here. It's equivalent to:

argumentLength="=$((argumentLength - 1))"

That's why the error message says =3.

Upvotes: 2

Related Questions