Shell Tips 9: Testing $?

February 14, 2011

There is a built in shell variable $? which
gives the return value — the success or failure —
of the most recently executed command. (Functions and
builtins return such results, although we are usually interested in the
result of an executable).
Don’t do this:

someprocess someargument
if [ $? = 0 ]
echo "success"

it can be more concisely written as:

if someprocess someargument
echo "success"

Why? Note the lack of square brackets.
The “if” construct was originally designed to detect the
success or failure of a command, and the value for success
is 0. It was extended by the [] construct to do more
general boolean aalgebra, where 0 corresponds to false, and
non-zero to true–the other way round.
So in the first block of code, the command is retrutng
0 meaning success, which is then compared to 0 to turn it
into a boolean true or non-zer0, which is then autiomaticallly
converted back to a 0 by the left angle bracket!


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: