Linux Know-How provides a collection of introductory texts on often needed Linux skills.


Simple applications of if

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:

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

anny ~>

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:

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

anny > echo $?
0

anny >

The same result can be obtained as follows:

anny > grep $USER /etc/passwd

anny > if [ $? -ne 0 ] ; then echo "not a local account" ; fi
not a local account

anny >

Numeric comparisons

The examples below use numerical comparisons:

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

anny > echo $num
201

anny > if [ "num" > 150 ]
More input> then echo ; echo "you've worked hard enough for today."
More input> echo ; fi

you've worked hard enough for today.


anny >

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

#!/bin/bash

# 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, ....." | mail -s "Garbage cans out" your@your_domain.org

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;
fi

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

Regular expressions may also be used:

anny > gender="female"

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

anny >

See the info pages for Bash for more information on pattern matching with the "(( EXPRESSION ))" and "[[ EXPRESSION ]]" constructs.


Last Update: 2010-12-16