34

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.

peterh
  • 9,731
Rahul Prasad
  • 451
  • 1
  • 4
  • 7
  • 1
    Refer to this links: - http://stackoverflow.com/questions/4470349/execute-command-in-bash-with-parameter-and-return-value - http://bash.cyberciti.biz/guide/The_exit_status_of_a_command - http://bencane.com/2014/09/02/understanding-exit-codes-and-how-to-use-them-in-bash-scripts/ Hope these links help. –  Jun 11 '15 at 02:17

2 Answers2

50

&& 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.

John1024
  • 74,655
10

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.

polemon
  • 11,431
  • 3
    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 04:17
  • 1
    0 is when program exits successfully. Non zero is errors or failures. adding ! helped, thanks @lcd047 for suggesting. – Rahul Prasad Jun 11 '15 at 05:21
  • @lcd047 Right, I forgot the !. Thanks for noticing. – polemon Jun 11 '15 at 12:22