Bash - How to check if a Command Failed?

If you want to be sure that the command you executed on a Bash Shell did complete successfully or failed then you can make use of the below syntax.

Oneliner Syntax:
command && echo "The command was successful" || echo "The command failed"

Example:
bash-3.2$ whoami && echo "The command was successful" || echo "The command failed"

c2ctechtv
The command was successful

If this seems too long, you can use -1 for failure and 1 for success.


Example:
command && echo 1 || echo -1

If this is too much, then we can create an alias function that can make this super simplified.

Alias:
alias cstatus='function _cstatus() { "$@" && echo "Command succeeded" || echo "Command failed"; }; _cstatus'

Now if you run any command with the prefix cstatus, you will get a string to indicate if the command succeeded or failed.


Example:
bash-3.2$ cstatus whoami
c2ctech
Command succeeded

bash-3.2$ cstatus whoamaa
bash: whoamaa: command not found
Command failed
Check if a Bash Command Failed with Example

Comments & Discussion

Facing issues? Have questions? Post them here! We're happy to help!