Linux 标准退出状态码

2021/07/08

Linux 标准退出状态码

在Linux中,当程序中断后,会返回一个退出码。如果是正常退出,那么这个码将会是零,任何非零的情况都意味着有错误产生。

退出码在我们自己的程序中是可以任意选择并指定的,但有些约定俗成的规矩,部分退出码有明确的含义,尽量不要使用。

我们一般在shell里通过 exit number,像是 exit 42,的方式指定退出码,在标准的输出时是隐藏的,可以通过 echo $? 的方式查询上一条指令的运行状态,这也常常作用在 shell 脚本中对某个指令运行状况的检测。

特殊的退出码

General Error: 1
This is the most used exit code and should be used as a catch-all value for miscellaneous errors.
Misuse of Shell Built-in: 2
Exit code 2 signifies invalid usage of some shell built-in command. Examples of built-in commands include alias, echo, and printf.
Cannot Execute: 126
In this case, the command invoked can’t be executed. This will most likely occur when there’s a permission problem or the command isn’t executable.
Command Not Found: 127
A command couldn’t be found. This may happen, for example, because there was a typo or an issue with our PATH.
Invalid Argument To Exit: 128
The exit command only takes a positive integer as its argument. This means any negative, fractional, or non-numeric values aren’t allowed.
Fatal Error Signal ‘n‘: 128+n
In Linux, programs might send one of 33 different signals. When a program terminates after receiving one of these signals, it will return an error code equal to 128 + signal-number.

For example, when we terminate a program by typing Control-C, we’re effectively sending it a SIGINT signal. This signal has a value of 2, therefore, the program will stop its execution and return an exit code with a value 128 + 2 = 130.
Exit Status Out of Range: 255
Depending on our shell, exit code 255 might mean that the returned exit code is outside of the 0-255 range.

不要使用255以上的退出码。

Search

    Table of Contents