Get return value of command "mv -n" linux

Viewed 2117

From mv --help

-n, --no-clobber do not overwrite an existing file

user@pc:~/Desktop/test$ ls -l
total 16
-rw-r--r-- 1 user user 0 ago  6 20:28 bla
-rw-r--r-- 1 user user 0 ago  6 20:28 ble
user@pc:~/Desktop/test$ mv -n bla ble
user@pc:~/Desktop/test$

Is there a way to check the return value of the command mv -n?

Is it possible to do something similar to $? to know if the command succeeded (returned 0) in moving the file or failed (returned 1) because there is already another file with the same name in the target folder?

3 Answers

No, $? won't tell you if the -n option prevented mv from doing the move since the exit status will be 0 in this case.


Solution 1: you can check that the original file didn't move...

mv -n file1 file2
[ -e file1 ] && echo "Hmmm, mv didn't have any effect"

However there is a possibility of a race condition if another program recreates file1 in the meantime between the move and your test.


Solution 2: since you seem to use GNU mv, the -v option can be helpful to find out if the move succeeded

if mv -v -n file1 file2 | grep -q .; then
    echo "The move succeeded"
fi

With -v, if the move occurs, mv will output renamed 'file1' -> 'file2'. Piping its output to grep -q . tests whether mv output anything on its standard output.

If there is an error, mv will output on its standard error and the grep will fail too.

Rather than trying to do the move and then testing for the move failing because the destination file exists, just test for the destination file existing before trying to do the move, e.g.:

[[ ! -f ble ]] && mv bla ble || { ret=$?; echo "failed to move bla to ble: $ret" >&2; exit "$ret"; }

That will output the error message if ble exists or the mv fails and it exits on a failure, massage to suit, e.g. maybe you'd prefer:

[[ -f ble ]] && { ret=$?; echo "warning ble exists so skipping it" >&2; }
[[ $ret == 0 ]] && mv bla ble

or a simple if-else:

if [[ -f ble ]]; then
    echo "warning ble exists so skipping it" >&2
else
    mv bla ble
fi
Related