How do I run a command only after previous command is unsuccessful in bash?

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


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.