To a first approximation, 0 is success, non-zero is failure, with 1 being general failure, and anything larger than one being a specific failure. Aside from the trivial exceptions of false and test, which are both designed to give 1 for success, there’s a few other exceptions I found.
More realistically, 0 means success or maybe failure, 1 means general failure or maybe success, 2 means general failure if 1 and 0 are both used for success, but maybe success as well.
The diff command gives 0 if files compared are identical, 1 if they differ, and 2 if binaries are different. 2 also means failure. The less command gives 1 for failure unless you fail to supply an argument, in which case, it exits 0 despite failing.
The more command and the spell command give 1 for failure, unless the failure is a result of permission denied, nonexistent file, or attempt to read a directory. In any of these cases, they exit 0 despite failing.
Then the expr command gives 1 for success unless the output is the empty string or zero, in which case, 0 is success. 2 and 3 are failure.
Then there’s cases where success or failure is ambiguous. When grep fails to find a pattern, it exits 1, but it exits 2 for a genuine failure (like permission denied). klist also exits 1 when it fails to find a ticket, although this isn’t really any more of a failure than when grep doesn’t find a pattern, or when you ls an empty directory.
So, unfortunately, the Unix powers that be don’t seem to enforce any logical set of rules, even on very commonly used executables.
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 ${PIPESTATUS[@]} 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 errorsMiscellaneous errors, such as «divide by zero» and other impermissible operations.
Example:
$ let "var1 = 1/0"; echo $? -bash: let: var1 = 1/0: division by 0 (error token is "0") 1 -
2— Misuse of shell builtins (according to Bash documentation)Missing keyword or command, or permission problem (and diff return code on a failed binary file comparison).
Example:
empty_function() {} -
6— No such device or addressExample:
$ curl foo; echo $? curl: (6) Could not resolve host: foo 6 -
124— command times out 125— if a command itself failssee: coreutils-
126— if command is found but cannot be invoked (e.g. is not executable)Permission problem or command is not an executable.
Example:
$ /dev/null $ /etc/hosts; echo $? -bash: /etc/hosts: Permission denied 126 -
127— if a command cannot be found, the child process created to execute it returns that statusPossible problem with
$PATHor a typo.Example:
$ foo; echo $? -bash: foo: command not found 127 -
128— Invalid argument toexitexit takes only integer args in the range 0 — 255.
Example:
$ exit 3.14159 -bash: exit: 3.14159: numeric argument required -
128—254— fatal error signal «n» — command died due to receiving a signal. The signal code is added to 128 (128 + SIGNAL) to get the status (Linux:man 7 signal, BSD:man signal), few examples below: -
130— command terminated due to Ctrl-C being pressed, 130-128=2 (SIGINT)Example:
$ cat ^C $ echo $? 130 -
137— if command is sent theKILL(9)signal (128+9), the exit status of command otherwisekill -9 $PPIDof script. -
141—SIGPIPE— write on a pipe with no readerExample:
$ 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 ${PIPESTATUS[@]} 0 125 141 -
143— command terminated by signal code 15 (128+15=143)Example:
$ sleep 5 && killall sleep & [1] 19891 $ sleep 100; echo $? Terminated: 15 143 -
255* — exit status out of range.exit takes only integer args in the range 0 — 255.
Example:
$ 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).
See:
- Appendix E. Exit Codes With Special Meanings at Advanced Bash-Scripting Guide
- Writing Better Shell Scripts – Part 2 at Innovationsts
Я новый пользователь системы Linux. Как мне получить код завершения команды?
Как получить код вывода или статус команды оболочки Linux или Unix и сохранить его в переменной оболочки?
Введение. Каждая команда оболочки Linux или Unix возвращает состояние, когда она завершается нормально или ненормально.
Например, если скрипт backup.sh не выполнен, и он возвращает код, который сообщает скрипту оболочки отправить электронное письмо админу.
Что такое код вывода в оболочке bash?
Каждая команда Linux или Unix, выполняемая скриптом оболочки или пользователем, имеет статус вывода.
Статус вывода – это целое число.
0 состояние выхода означает, что команда была успешной без каких-либо ошибок.
Ненулевое (1-255 значений) состояние выхода означает, что команда была неудачной.
Как узнать код вывода команды
Вам нужно использовать определенную переменную оболочки с именем $? чтобы получить статус вывода из ранее выполненной команды.
Выведем $? переменной используя команду echo или команду printf:
date echo $? 0 date-foo-bar printf '%dn' $? 127
Из приведенных выше выводов ясно, что код вывода 0 означает, что команда date была успешной.
Кроме того, код вывода – 127 (не ноль), так как команда nonexistant не была успешной.
Bash как получить код завершения команды – Как использовать коды вывода в скриптах оболочки
Итак, как вы сохранить статус вывода команды в переменной оболочки?
Просто назначьте $? в переменную оболочки. Синтаксис:
command status=$? ## run date command ## cmd="date" $cmd ## get status ## status=$? ## take some decision ## [ $status -eq 0 ] && echo "$cmd command was successful" || echo "$cmd failed"
Как мне установить код вывода для моих собственных скриптов оболочки?
Команда exit вызывает обычное завершение скриптов оболочки.
Вывод из оболочки со статусом N. Синтаксис:
#!/bin/bash /path/to/some/command [ $? -eq 0 ] || exit 1
Пример скрипта оболочки для получения кода завершения команды
#!/bin/bash # # Sample shell script to demo exit code usage # # set -e ## find ip in the file ## grep -q 192.168.2.254 /etc/resolv.conf ## Did we found IP address? Use exit status of the grep command ## if [ $? -eq 0 ] then echo "Success: I found IP address in file." exit 0 else echo "Failure: I did not found IP address in file. Script failed" >&2 exit 1 fi
Заключение
На этой странице показано, как использовать коды вывода в системах на основе Linux или Unix и как получить статус вывода / код команды.