Understanding Exit Codes in Bash: A Guide to Handling Command Execution Results


How to check exit codes in bash Linux. You can not see the numeric codes unless you want to. If you're going to see the numeric exit code use echo $? command.

In Bash, the exit code of a command or script is stored in a special variable called $?. The exit code indicates the success or failure of the previous command or script. Conventionally, an exit code of 0 means success, while a non-zero exit code indicates an error or failure.

Recommended Read: 

What are Exit Codes?

Exit codes are numeric values that represent the status of a command execution in Bash. A zero (0) exit code typically indicates a successful execution, while non-zero values signify different types of errors or failures. By analyzing these exit codes, you can determine whether a command completed successfully or encountered issues during execution.

 For example check exit codes in bash

 abc the command error message will tell you there is no "abc" script in your bin directory.

$ bin/abc

$ echo $?


On the Linux command line most commands the exit code will be 0.

$ pwd
$ echo $?

Example the exit code 1 as below:

$ ls -lR /usr > /dev/null 2>&1
$ echo $?

I start a second shell, exit it and then display the exit code.

$ bash            # start new shell
$ exit 123
$ echo $?

If you ping a system which doesn’t exist on your network or isn’t responding for some reason as example below:

$ ping
$ echo $?

You can get the exit code with a particular code by include an exit command as below:

$ cat test
echo Hello, World huuphan.com
exit 12
$ ./test
Hello, World huuphan.com
$ echo $?


Understanding and checking exit codes in Bash is crucial for effective error handling and decision making in your scripts. By analyzing the exit code of a command, you can determine whether it succeeded or encountered issues during execution. This information allows you to build intelligent workflows, taking different actions based on the exit code results. More details please refer to Linux


Popular posts from this blog

zimbra some services are not running [Solve problem]

Bash script list all IP addresses connected to Server

How to install php7 on centos 6