Understanding Exit Codes in Bash: A Guide to Handling Command Execution Results
Introduction
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:
- Change Group Ownership in Linux with the chgrp Command
- Install and use htop command in Linux
- Check exit codes in bash
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
exit
$ echo $?
123
If you ping a system which doesn’t exist on your network or isn’t responding for some reason as example below:
$ ping 192.168.1.111
$ echo $?
You can get the exit code with a particular code by include an exit command as below:
$ cat test
#!/bin/bash
echo Hello, World huuphan.com
exit 12
$ ./test
Hello, World huuphan.com
$ echo $?
12
Conclusion
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
Comments
Post a Comment