Run a Command Only If the Previous One Fails


||

The && runs each command in sequence only if the previous one completes successfully. The || does the opposite: If the first command fails (technically, it returns an exit status that is not 0), only then does the second one run. Think of it like the words either/oreither run the first command or the second one.

The || is often used to send an alert to an administrator when a process stops. For instance, to ensure that a particular computer is up and running, an administrator might constantly query it with the ping command (you'll find out more about ping in Chapter 14, "Connectivity"); if ping fails, an email is sent to the administrator to let him know.

ping -c 1 -w 15 -n 72.14.203.104 || {     echo "Server down"  | mail -s 'Server down' admin@google.com } 


Note

Wondering what the | is? Look ahead in this chapter to the "Use the Output of One Command As Input for Another" section to find out what it is and how to use it.


With just a bit of thought, you'll start to find many places where || can help you. It's a powerful tool that can really prove useful.



Linux Phrasebook
Linux Phrasebook
ISBN: 0672328380
EAN: 2147483647
Year: 2007
Pages: 288

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net