Tip Of The Week

This fragment of shell doesn't do what you'd expect at a quick glance:

if [ $? -ne 0 ]; then
    exit $?
fi

The act of checking $? causes $? to be set to the result of the test, so this executes exit 0 if $? is non-zero.

NP: Cosmos, Murcof

11:20 Friday, 17 Aug 2007 [#] [computers] (5 comments)

Posted by Bastien at Fri Aug 17 12:19:08 2007:
Except if "[" is builtin I would guess.
Posted by Ralf Wildenhues at Fri Aug 17 12:33:00 2007:
It does not matter whether "[" is builtin or not.

The shell snippet in question is shorter written as

  || exit $?

(with prior newlines deleted, so that the syntax is valid).
Posted by Andrew at Fri Aug 17 14:06:09 2007:
It's probably best to post the solution as well as the problem. But prehaps that's just me.

i.e. Something like:

retval=$?
if [ $retval -ne 0 ]; then
  exit $retval
fi
Posted by Andrew at Fri Aug 17 14:06:46 2007:
Or perhaps it's "perhaps"...
Posted by Ross at Fri Aug 17 14:15:47 2007:
In this situation I don't really care what $? was (it was after calling apt-get, so $? is always 0 or 100), so I switched it to exit 1.

Yes, using ||exit $? would be another good solution.

Name:


E-mail:


URL:


Add 5 and 1 (required):


Comment: