Testing the Exit Status of a Command

by mike on November 3, 2011

test
The test command is used to determine exit status on numerous tests that can be performed in scripts. The test command does not produce any output it simply is checking for the exit status.  Note if you use variables with test be sure to enclose them in double quotes so the test receives an argument.

if [ “$file”  ] ...

The test command acts as a control structure, in other words it alters the order of execution of commands.  One set of commands is executed if true, another set of commands is executed if false.  The test command is a builtin command that uses an if structure at the start of the script to verify that you have entered at least one argument.

The Test Command

The test command uses many different expressions or options to test with.

The symbol “[” is a symbolic link to test and is a shell builtin.

type [
[ is a shell builtin

You can test the outcome of any command using “echo $?” after the command has executed.  In this example, the semi-colon is used to execute the command on the same line.  You can see the output is “0” or success.

who; echo $?
2009-07-20 18:18 (:0)
mike     pts/0        2009-07-20 18:19 (:0.0)
mike     pts/1        2009-07-20 18:25 (:0.0)
0

This same testing process is easily done in shell scripts.  In this example, an attempt to ping an IP Address fails with the exit code of “2”.

#!/bin/bash
ping -c3 123.123.123.123
echo $?

sh test.sh
connect: Network is unreachable
2

Now change it to a successful connection and you not only get command output but the test is successful.

#!/bin/bash
ping -c3 127.0.0.1
echo $?

sh test.sh
PING 127.0.0.1 (127.0.0.1) 56(84) bytes of data.
64 bytes from 127.0.0.1: icmp_seq=1 ttl=64 time=0.078 ms
64 bytes from 127.0.0.1: icmp_seq=2 ttl=64 time=0.070 ms
64 bytes from 127.0.0.1: icmp_seq=3 ttl=64 time=0.072 ms

— 127.0.0.1 ping statistics —
3 packets transmitted, 3 received, 0% packet loss, time 1998ms
rtt min/avg/max/mdev = 0.070/0.073/0.078/0.007 ms
0

Comments on this entry are closed.

Previous post:

Next post: