Understanding exit codes on Linux

Exit codes on the Linux command line are numeric values that provide feedback on whether the command just run was successful or ran into some variety of problem. If you’ve never noticed them, don’t be surprised. The more obvious error messages like “command not found” will generally tell you all you need to know when something goes wrong, but the stealthy exit codes have a distinct advantage. For one thing, they can be checked in scripts to note errors that might be encountered (more on this below).

To get started, sit down at your Linux system and open a terminal window. Then type “pwd”. You should be rewarded by a quick display of your current location in the file system – undoubtedly your home directory. Before you do anything else, however, type “echo $?”. The system should result in the display of a zero (0). Yes, that’s the exit code and it’s meant to indicate that the pwd command you just used ran without any errors. An exit code of 0 always indicates that no problems were encountered.

Any exit code other than 0, on the other hand, indicates that some problem occurred. What problem depends on the command that was run. Executables don’t always use the same code for the same problem. The numeric range for exit codes is 0-255, so any code from 1-255 means something went wrong. Here’s a list of some of the exit codes that you might run into from time to time.

Code	Description
0	success
1	generic error
2	syntax error
126	permissions issue -- the requested command (file) can't be executed
	(but was found)
127	command (file) not found
128	fatal error, amount above 128 is signal number
128 + N	the shell was terminated by the signal N (also used like this by 
	various other programs)
130	process terminated by SIGINT (^c on keyboard)
137	process terminated by SIGKILL
143	process terminated by SIGTERM
255	wrong argument to the exit builtin (see code 128)

Now let’s run some tests and see how this works.

First, we’ll try to display a file that doesn’t exist – leading to an exit code of 1.

$ cat noSuchFile
cat: noSuchFile: No such file or directory
$ echo $?
1

Next, we’ll try to list the same nonexistent file.



Source link