How can you check the exit status of a bash script? What exit code does an unsuccessful script return, and why?
Asked at
AI answer
The exit code of the last command run can be checked using $?; check it immediately, because the next command overwrites the value:
./script.sh
status=$?
printf 'exit code: %d\n' "$status"
Success is usually indicated by code 0, and failure by any nonzero code. There is no universal error code: 1 is often used as a general error, while specific values may have special meanings. A script exits with the code of the last command run unless exit N is called; therefore, a failure in an intermediate command does not by itself guarantee a nonzero final exit code. You can check with if ./script.sh; then ...; else ...; fi. set -e can terminate a script when a command fails, but it has exceptions and subtleties, so critical errors are more reliably handled explicitly.
Also asked at RWB
- Why did you decide to change jobs / leave your current company?
- What is the key difference between TCP and UDP?
- What is the difference between git merge and git rebase? When should each approach be used?
- What is an inode in Linux?
- Which command is used to determine the route of a packet from your device to the target host?
Similar questions
- What is an exit code, and how can you find out what it is?
- Have you ever written a SIGTERM handler in Bash or Python?
- How can you view the last 30 (or 100) lines of a log and search it for errors using Linux commands?
- How to implement a condition in bash where one of two commands or conditions is executed?
- How can an error be logged into a log file when executing a bash script?