9

This question already has an answer here:

We use && operator to run a command after previous one finishes.

update-system-configuration && restart-service

but how do I run a command only if previous command is unsuccessful ? For example If I have to update system configuration and if it fails I need to send a mail to system admin ?

Edit: Come on this is not a duplicate question of control operators. This will help users who are searching for specifically this, I understand that answer to control operators will answer this question too, but people searching specifically for how to handle unsuccessful commands won't reach there directly, otherwise I would have got there before asking this question.

marked as duplicate by G-Man, cuonglm, Anthon, Ramesh, Stephen Kitt Jun 11 '15 at 4:41

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

11

&& executes the command which follow only if the command which precedes it succeeds. || does the opposite:

update-system-configuration || echo "Update failed" | mail -s "Help Me" admin@host

Documentation

From man bash:

AND and OR lists are sequences of one of more pipelines separated by the && and || control operators, respectively. AND and OR lists are executed with left associativity. An AND list has the form

command1 && command2

command2 is executed if, and only if, command1 returns an exit status of zero.

An OR list has the form

command1 || command2

command2 is executed if and only if command1 returns a non-zero exit status. The return status of AND and OR lists is the exit status of the last command executed in the list.

2

When with "successful" you mean it returns 0, then simply test for it:

if ! <command>; then
    <ran if unsuccessful>
fi

The reason this works, is because as a standard, programs should return nonzero if something went wrong, and zero if successful.

Alternatively, you could test for the return variable $?:

<command>
if [ $? -ne 0 ]; then
    <ran if unsuccessful>
fi

$? saves the return code from the last command.

Now, if is usually a shell built-in command. So, depending what shell you're using, you should check the man page of your shell for that.

  • 1
    You got the first case wrong, it's if command; then echo successful; fi, and if ! command; then echo unsuccessful; fi. The condition for if when checking exit codes is reversed. – lcd047 Jun 11 '15 at 4:17
  • 0 is when program exits successfully. Non zero is errors or failures. adding ! helped, thanks @lcd047 for suggesting. – Rahul Prasad Jun 11 '15 at 5:21
  • @lcd047 Right, I forgot the !. Thanks for noticing. – polemon Jun 11 '15 at 12:22

Not the answer you're looking for? Browse other questions tagged or ask your own question.