To Test Or Not To Test?

        Submitter: Oleg Goldshmidt

        Language: bash

        Date:        2005/01/17

 What is the difference between

test -f foo && /bin/chmod 755 foo
and
if [ -f foo ];
then /bin/chmod 755 foo
fi

in a shell script? If you think that the result is the same, think again. The side effect is the same (foo's permissions are changed if the file exists), but the result, i.e. the return code of the statement, may actually be different (if foo does not exist). 

If you still think it is silly try this:

#!/bin/bash

function die() {
echo "DEAD!"
exit 1
}

function test_one() {
if [ -f foo ]; then /bin/chmod 755 foo; fi
}

function test_two() {
test -f foo && /bin/chmod 755 foo
}

trap die ERR

if [ $1 -eq 1 ]
then test_one
else test_two
fi

echo "ALIVE!"

- pass the script 1 and 2 on the command line and observe the difference. 

Yes, it happened to me. Was caught in testing, fortunately. By a colleague. Didn't I say my code sucked?