About nixCraft

Topics

Howto display error message instantly when command fails

Posted by Vivek Gite [Last updated: March 22, 2007]

While writing a shell script you may need to display an error message. For example if you failed to open /etc/passwd file you want to display error message.

Old way

You can write something as follows:
cat /etc/shadow 2>/dev/null
if [ $? -ne 0 ]; then echo "Failed to open file"; exit1 ; fi

New way - OR || control operator

However you can use control operator || (or lists). It has the form:
command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. For example:
$ cat /etc/shadow 2>/dev/null || echo “Failed to open file”

This way you display error message. Another option is to create die function:

#!/bin/bash
function die(){
 echo $1
 exit 1
}
# ...
# ... other code
cat /etc/shadow 2>/dev/null || die “Failed to open file”
# rest of script

AND && control operator

Similarly you can use AND (&&) control operator. It has the form:
command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.
$ cat /etc/shadow 2>/dev/null && echo "I can open /etc/shadow file"

You can combine both to produce useful message in a script:
#!/bin/bash
...
tar -zcf /dev/st0 /data2 && echo "/data2 added to backup device" || echo "Warning: Cannot add /data2 to backup device"
....

E-mail this to a friend      Printable version

You may also be interested in other helpful articles:

Leave a Reply

We encourage your comments, and suggestions. But please stay on topic, be polite, and avoid spam. Thank you very much for stopping by our site!

XHTML: You can use these tags: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>

*
To prove you're a person (not a spam script), type the security word shown in the picture. Click on the picture to hear an audio file of the word.
Click to hear an audio file of the anti-spam word

Copyright © 2004-2008 nixCraft. All rights reserved - TOS/Disclaimer - Privacy policy - Sitemap - Powered by Open source software.