Thursday, July 31, 2008

Running Commands Conditionally

in Linux every command you run produces and records an exit status on whether the command was successful or not. If a command is successful the exit status will be recorded as "0" and if the command is not successful then the exit status is recorded as any number between "1 and 255". The exit status of the last command that you ran is recorded inside the $? variable.
To see what the exit status was of your previous command simply type echo $?
were this is useful is it allows you to run commands conditionally, based on the commands exit status. When you type two commands and you separate them with a && the second command will only run if the first command produced an exit status of "0" ie was successful.
If you separate the commands with a || then the second command will only run if the first command produced an exit status of "1-255" ie was not successful.
eg
ping 192.168.0.1 -c1 -w2 && echo "host is up"

- c1 = send 1 ping packet
-w2 = wait 2 seconds for a response

will display "host is up" if the ping command was successful at reaching the host at 192.168.0.1 and
ping 192.168.0.1 -c1 -w2 || echo "host is down"

will display "host is down" if the ping command was unsuccessful in reaching the host at 192.168.0.1

to get the desired result you should combine the commands like so

ping 192.168.0.1 -c1 -w2 && echo "host is up" || echo "host is down"

since you don't care about the actual output of the ping command (you are only interested if it was succesful or not ) You can redirect stdout and stderror to /dev/null so your final command would be something like:
ping 192.168.0.1 -c1 -w2 &> /dev/null && echo "Host is up" || echo "Host is Down"

No comments: