- How do I get the list of exit codes (and/or return codes) and meaning for a command/utility?
- 4 Answers 4
- Bash Exit Code of Last Command
- Bash Exit Code
- Checking Bash Exit Code
- Incorporating Exit Code in Scripts
- Exit Code Value Explanation
- Defining Exit Status in Script
- Final Thoughts
- About the author
- Sidratul Muntaha
- Как определить статус завершения скрипта или команды в Linux
How do I get the list of exit codes (and/or return codes) and meaning for a command/utility?
Is there a way I can do what stated in the title from the terminal commands, or will I have to look into the codes?
4 Answers 4
Exit codes indicates a failure condition when ending a program and they fall between 0 and 255. The shell and its builtins may use especially the values above 125 to indicate specific failure modes, so list of codes can vary between shells and operating systems (e.g. Bash uses the value 128+N as the exit status). See: Bash — 3.7.5 Exit Status or man bash .
In general a zero exit status indicates that a command succeeded, a non-zero exit status indicates failure.
To check which error code is returned by the command, you can print $? for the last exit code or $ which gives a list of exit status values from pipeline (in Bash) after a shell script exits.
There is no full list of all exit codes which can be found, however there has been an attempt to systematize exit status numbers in kernel source, but this is main intended for C/C++ programmers and similar standard for scripting might be appropriate.
Some list of sysexits on both Linux and BSD/OS X with preferable exit codes for programs (64-78) can be found in /usr/include/sysexits.h (or: man sysexits on BSD):
0 /* successful termination */ 64 /* base value for error messages */ 64 /* command line usage error */ 65 /* data format error */ 66 /* cannot open input */ 67 /* addressee unknown */ 68 /* host name unknown */ 69 /* service unavailable */ 70 /* internal software error */ 71 /* system error (e.g., can't fork) */ 72 /* critical OS file missing */ 73 /* can't create (user) output file */ 74 /* input/output error */ 75 /* temp failure; user is invited to retry */ 76 /* remote error in protocol */ 77 /* permission denied */ 78 /* configuration error */ /* maximum listed value */
The above list allocates previously unused exit codes from 64-78. The range of unallotted exit codes will be further restricted in the future.
However above values are mainly used in sendmail and used by pretty much nobody else, so they aren’t anything remotely close to a standard (as pointed by @Gilles).
In shell the exit status are as follow (based on Bash):
- 1 — 125 — Command did not complete successfully. Check the command’s man page for the meaning of the status, few examples below:
- 1 — Catchall for general errors
$ let "var1 = 1/0"; echo $? -bash: let: var1 = 1/0: division by 0 (error token is "0") 1
Missing keyword or command, or permission problem (and diff return code on a failed binary file comparison).
$ curl foo; echo $? curl: (6) Could not resolve host: foo 6
$ /dev/null $ /etc/hosts; echo $? -bash: /etc/hosts: Permission denied 126
$ foo; echo $? -bash: foo: command not found 127
$ exit 3.14159 -bash: exit: 3.14159: numeric argument required
$ hexdump -n100000 /dev/urandom | tee &>/dev/null >(cat > file1.txt) >(cat > file2.txt) >(cat > file3.txt) >(cat > file4.txt) >(cat > file5.txt) $ find . -name '*.txt' -print0 | xargs -r0 cat | tee &>/dev/null >(head /dev/stdin > head.out) >(tail /dev/stdin > tail.out) xargs: cat: terminated by signal 13 $ echo $ 0 125 141
$ sleep 5 && killall sleep & [1] 19891 $ sleep 100; echo $? Terminated: 15 143
$ sh -c 'exit 3.14159'; echo $? sh: line 0: exit: 3.14159: numeric argument required 255
According to the above table, exit codes 1 — 2, 126 — 165, and 255 have special meanings, and should therefore be avoided for user-specified exit parameters.
Please note that out of range exit values can result in unexpected exit codes (e.g. exit 3809 gives an exit code of 225, 3809 % 256 = 225).
Bash Exit Code of Last Command
When a bash command is executed, it leaves behind the exit code, irrespective of successful or unsuccessful execution. Examining the exit code can offer useful insight into the behavior of the last-run command.
In this guide, check out how to check bash exit code of the last command and some possible usages of it.
Bash Exit Code
Every UNIX/Linux command executed by the shell script or user leaves an exit status. It’s an integer number that remains unchanged unless the next command is run. If the exit code is 0, then the command was successful. If the exit code is non-zero (1-255), then it signifies an error.
There are many potential usages of the bash exit code. The most obvious one is, of course, to verify whether the last command is executed properly, especially if the command doesn’t generate any output.
In the case of bash, the exit code of the previous command is accessible using the shell variable “$?”.
Checking Bash Exit Code
Launch a terminal, and run any command.
Check the value of the shell variable “$?” for the exit code.
As the “date” command ran successfully, the exit code is 0. What would happen if there was an error?
Let’s try running a command that doesn’t exist.
It’s a non-zero value, indicating that the previous command didn’t execute properly.
Now, have a look at the following command:
When working with a command that has one or more pipes, the exit code will be of the last code executed in the pipe. In this case, it’s the grep command.
As the grep command was successful, it will be 0.
In this example, if the grep command fails, then the exit code will be non-zero.
Incorporating Exit Code in Scripts
The exit code can also be used for scripting. One simple way to use it is by assigning it to a shell variable and working with it. Here’s a sample shell script that uses the exit code as a condition to print specific output.
$ #!/bin/bash
$ echo «hello world»
$ status = $?
$ [ $status -eq 0 ] && echo «command successful» || echo «command unsuccessful»
When being run, the script will generate the following output.
Now, let’s see what happens when there’s an invalid command to run.
$ #!/bin/bash
$ random-command
$ status = $?
$ [ $status -eq 0 ] && echo «command successful» || echo «command unsuccessful»
When being run, the output will be different.
Exit Code Value Explanation
When the exit code is non-zero, the value ranges from 1 to 255. Now, what does this value mean?
While the value is limited, the explanation of each value is unique to the program/script. For example, “ls” and “grep” has different explanations for error code 1 and 2.
Defining Exit Status in Script
When writing a script, we can define custom exit code values. It’s a useful method for easier debugging. In bash scripts, it’s the “exit” command followed by the exit code value.
Per the convention, it’s recommended to assign exit code 0 for successful execution and use the rest (1-255) for possible errors. When reaching the exit command, the shell script execution will be terminated, so be careful of its placement.
Have a look at the following shell script. Here, if the condition is met, the script will terminate with the exit code 0. If the condition isn’t met, then the exit code will be 1.
$ #!/bin/bash
$ if [ [ » $(whoami) » ! = root ] ] ; then
$ echo «Not root user.»
$ exit 1
$ fi
$ echo «root user»
$ exit 0
Verify the result of running this script without sudo privilege or “root” user.
Final Thoughts
This guide demonstrates what exit codes are and how you can use them. It also demonstrates how to assign appropriate exit codes in a bash script.
Interested in bash scripting? One of the easiest ways to get started is by writing your own scripts. Check out this simple guide on how to write a simple bash script.
About the author
Sidratul Muntaha
Student of CSE. I love Linux and playing with tech and gadgets. I use both Ubuntu and Linux Mint.
Как определить статус завершения скрипта или команды в Linux
В Linux/Unix когда вы запускаете скрипт или команду, они завершатся со значимым статусом для того чтобы вы поняли — достигли ли вы своей цели запуская их или нет. Тем самым мы можем предпринять какие-то действия по статусу завершения (выполнено, провалено или выполнено частично) этих команд. В linux есть некоторые команды, которые не отображают статус завершения, например команда «mount -a» которую мы выполняем после правки файла fstab не покажет вам ничего. Так как же мы узнаем что команда отработала и на сколько успешно? Для этого в Linux/Unix есть встроенная переменная которая хранит статус завершения для любой команды или запущенного скрипта. Этот статус хранится во встроенной переменно «$?». Статус завершения принимает значение от 0 до 255. Некоторые из обычно используемых статусов завершения приведены ниже.
0 Успешное выполнение команды 1 Команда завершилась неудачей во время расширения или перенаправления, статус завершения больше ноля. 2 Некорректное использование команды 126 Команда найдена, но не выполнена 127 Команда не найдена
Несколько примеров того, как использовать статусы завершения.
Как можно использовать статус завершения для проверки команды? Запустите команду которую хотите проверить, затем выполните команду
для проверки статус выполнения команды.
mirivlad@mirivlad:~⟫ ls New.doc mirivlad@mirivlad:~⟫ echo $? 0
Если вы получили статус завершения равный нулю, то команды была выполнена успешно.
Как можно использовать статус завершения в сценариях оболочки?
ls -lrt if [ $? -eq 0 ] then echo "команда ls -lrt выполнена успешно" else echo "команда ls -lrt не выполнена правильно, и статус завершения : $?" fi