BEEET Hvcw
BEEET Hvcw

Reputation: 49

Arithmetic comparison does not work in Bash

So, I have a script for moving files from one directory to another. I want to check whether the moving was successful or not, so I use this block of code:

...
mv "${!i}" "$dirname" 2>/dev/null
echo $?    # Check MV exit code
if (( $?==1 ))
then
...

The problem is that whether moving was successful or not, then does not work. If I do this instead

if (( $?==0 ))

it instead works in any case. I have read that it may be because $? is treated like a string, and strings have 0 value. However, if I change it to this

if (( $?=="1" ))

it does not work either. I have tried using [[ ... ]] and [ ... ] instead of (( ... )), and -eq instead of ==, removing and adding spaces, adding and removing quotes, but nothing worked.

What am I doing wrong? Maybe there is another way of responding to certain exit code?

Upvotes: 0

Views: 92

Answers (2)

Tyler Marshall
Tyler Marshall

Reputation: 488

The problem is here:

echo $?
if (( $?==1 ))

The first echo $? will echo the return value of your mv command; however, in the if statement, using $? again will give you the return value of the echo command! $? is always the return value of the last command. The last command is the echo and it is always succeeding so you are always getting a 0 return value in that if statement.

What you should do instead is save the value into a variable and then compare things to that variable:

mv "${!i}" "$dirname" 2>/dev/null
ret_val=$?
echo ${ret_val}
if (( ${ret_val}==1 ))

Upvotes: 6

Benjamin W.
Benjamin W.

Reputation: 52152

You can check the exit status of your command directly:

if mv "${!i}" "$dirname" 2>/dev/null; then
    # Code for successful move
else
    # Code for unsuccessful move
fi

Or, to keep the happy path less indented:

if ! mv "${!i}" "$dirname" 2>/dev/null; then
    # Code for unsuccessful move
    return 1 # Or maybe exit 1 if in a script, not a function
fi
# Code for successful move

As for how the exit status of echo messes up your code, Tyler's answer has that covered.

Upvotes: 3

Related Questions