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

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap