expressions in shell scripting

Testing exit status

The ? variable holds the exit status of the previously executed command (the most recently completed foreground process).

The following example shows a simple test:

myhome ~> if [ $? -eq 0 ]
More input> then echo ‘That was a good job!’
More input> fi
That was a good job!

myhome ~>

The following example demonstrates that TEST-COMMANDS might be any UNIX command that returns an exit status, and that if again returns an exit status of zero:

myhome ~> if ! grep $USER /etc/passwd
More input> then echo “your user account is not managed locally”; fi
your user account is not managed locally

myhome > echo $?

myhome >

The same result can be obtained as follows:

myhome > grep $USER /etc/passwd

myhome > if [ $? -ne 0 ] ; then echo “not a local account” ; fi
not a local account

myhome >

Numeric comparisons

The examples below use numerical comparisons:

myhome > num=`wc -l work.txt`

myhome > echo $num

myhome > if [ “$num” -gt “150” ]
More input> then echo ; echo “you’ve worked hard enough for today.”
More input> echo ; fi

you’ve worked hard enough for today.

myhome >

This script is executed by cron every Sunday. If the week number is even, it reminds you to put out the garbage cans:


# Calculate the week number using the date command:

WEEKOFFSET=$[ $(date +”%V”) % 2 ]

# Test if we have a remainder. If not, this is an even week so send a message.
# Else, do nothing.

if [ $WEEKOFFSET -eq “0” ]; then
echo “Sunday evening, put out the garbage cans.” | mail -s “Garbage cans out”

String comparisons

An example of comparing strings for testing the user ID:

if [ “$(whoami)” != ‘root’ ]; then
echo “You have no permission to run $0 as non-root user.”
exit 1;

With Bash, you can shorten this type of construct. The compact equivalent of the above test is as follows:

[ “$(whoami)” != ‘root’ ] && ( echo you are using a non-privileged account; exit 1 )

Similar to the “&&” expression which indicates what to do if the test proves true, “||” specifies what to do if the test is false.

Regular expressions may also be used in comparisons:

myhome > gender=”female”

myhome > if [[ “$gender” == f* ]]
More input> then echo “Pleasure to meet you, Madame.”; fi
Pleasure to meet you, Madame.

myhome >

Leave a Reply

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

You are commenting using your 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: