In Linux, an exit code indicates the response from the command or a script after execution. It ranges from 0 to 255. The exit codes help us determine whether a process ran:
Note: Exit codes are also known as return codes.
We can get the process's exit code once the command or script execution is complete using $?.
Here's an example:
root@educative:/# echo "Hello There!"Hello There!root@educative:/# echo $?0root@educative:/# cat demofile.txtcat: demofile.txt: No such file or directoryroot@educative:/# echo $?1
Note: The terminal is attached to the end of the shot. Please copy the commands from above and paste them into the terminal to try them.
In the above example:
echo “Hello There!” and it printed Hello There! on the following line. Then we ran the command echo $? and it provided output as 0, which indicates that the command ran successfully.cat demofile.txt, and it gave us an error cat: demofile.txt: No such file or directory, and the return code is 1, indicating a failure.Linux has some reserved exit codes with a special meaning. Here's the list of exit codes:
1: Catchall for general errors2: Misuse of shell built-ins (according to Bash documentation)126: Command invoked cannot execute127: “Command not found.”128: Invalid argument to exit128+n: Fatal error signal “n”130: Script terminated by Control-C255\*: Exit status out of rangeExit codes are usually used in the shell script to check the status and take actions accordingly. We run multiple commands in a shell script to check for an everyday use case and see if the command runs successfully. Here's an example:
# some_commandif [ $? -eq 0 ]; thenecho OKelseecho FAILfi
In the code above, we check if the return code is equal to 0. If it is, then we echo OK. Otherwise, we echo FAIL.