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: Rakesh
Author Info:

Rakesh is a seasoned developer with over 10 years of experience in web and app development, and a deep knowledge of operating systems. Author of insightful How-To articles for Code2care.

Follow him on: X





























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