Linux 中退出码的含义
退出码
![](/data/attachment/album/202308/03/154628oloxp7sl6s1z4pbl.jpg)



> 
> 揭开 Linux 中退出码的神秘面纱。了解什么是退出码，以及为什么和如何使用它们。
> 
> 
> 


退出码（退出状态）可以告诉我们最后一次执行的命令的状态。在命令结束以后，我们可以知道命令是成功完成的还是以错误结束的。


**其基本思想是，程序返回退出代码 `0` 时表示执行成功，没有问题。代码 `1` 或 `0` 以外的任何代码都被视为不成功。**


退出码除了 0 和 1 外还有很多值，我将在本文介绍它们。


### Linux Shell 中的各种退出码


我们来快速了解一下 Linux Shell 中的主要退出码：




| 退出码 | 解释 |
| --- | --- |
| `0` | 命令成功执行 |
| `1` | 通用错误代码 |
| `2` | 命令（或参数）使用不当 |
| `126` | 权限被拒绝（或）无法执行 |
| `127` | 未找到命令，或 `PATH` 错误 |
| `128+n` | 命令被信号从外部终止，或遇到致命错误 |
| `130` | 通过 `Ctrl+C` 或 `SIGINT` 终止（*终止代码 2 或键盘中断*） |
| `143` | 通过 `SIGTERM` 终止（*默认终止*） |
| `255/*` | 退出码超过了 0-255 的范围，因此重新计算（LCTT 译注：超过 255 后，用退出码对 256 取模） |



> 
> ? `130`（`SIGINT` 或 `^C`）和 `143`（`SIGTERM`）等终止信号是非常典型的，它们属于 `128+n` 信号，其中 `n` 代表终止码。
> 
> 
> 


在简单了解了退出码之后，我们来看看它们的用法。


### 获取退出码


前一个命令执行的退出码存储在 [特殊变量](https://linuxhandbook.com:443/bash-special-variables/) `$?` 中。你可以通过运行以下命令来获取：



```
echo $?

```

我们在所有演示中都将使用它来获取退出代码。


请注意，`exit` 命令支持以带着前一条命令相同的退出码退出。


### 退出码 0


退出码 `0` 表示命令执行无误，这是完成命令的理想状态。


例如，我们运行这样一条基本命令



```
neofetch 

echo $?

```

![](/data/attachment/album/202308/03/155020lpzz733zzjbmnb6z.png)


这个退出码 `0` 表示特定命令已成功执行，仅此而已。让我们再演示几个例子。


你可以尝试 [终止一个进程](https://itsfoss.com/how-to-find-the-process-id-of-a-program-and-kill-it-quick-tip/)；它也会返回代码 `0`。



```
pkill lxappearance

```

![](/data/attachment/album/202308/03/155022so77hadroxz7oh2r.gif)


查看文件内容也会返回退出码 0，这**仅**意味着 `cat` 命令执行成功。


### 退出码 1


退出码 `1` 也很常见。它通常表示命令以一般错误结束。


例如，在没有 sudo 权限的情况下使用 [软件包管理器](https://itsfoss.com/package-manager/)，就会返回代码 `1`。在 Arch Linux 中，如果我运行下面的命令：



```
pacman -Sy

```

它会返回 `1`， 表示上一条命令运行出错。


![exit code 1 (impermissible operation resulted in this code)](/data/attachment/album/202308/03/155022dgzy8ouyzrv7yavy.png)



> 
> ? 如果你在基于 Ubuntu 的发行版中尝试这样做（不使用 `sudo` 执行 `apt update`），运行后会得到错误码 `100`，表示你是在没有权限的情况下运行 `apt`。`100` 不是标准错误码，而是 `apt` 特有的错误码。
> 
> 
> 


虽然这是一般的理解，但我们也可以将其解释为 “不被允许的操作”。


除以 `0` 等操作也会返回错误码 `1`。


![Division by zero results in code 1](/data/attachment/album/202308/03/155022ozsa8g800aqd3505.png)


### 退出码 2


这个退出码出现在当执行的命令有语法错误时。滥用命令参数也会导致此错误。


一般来说，它表示由于使用不当，命令无法执行。


例如，我在一个本应只有一个连字符的选项上添加了两个连字符，那么此时会出现退出码 2。



```
grep --z file.txt

```

![Invalid argument resulted in exit code 2](/data/attachment/album/202308/03/155022oh0t2jp2tzttpro0.png)


当权限被拒绝时，比如访问 `/root` 文件夹，就会出现错误码 `2`。


![Permission denied gives out code 2](/data/attachment/album/202308/03/155023kfhzhz3du7dhv4qq.png)


### 退出码 126


126 是一个特殊的退出码，它用于表示命令或脚本因权限错误而未被执行。


当你尝试执行没有执行权限的 Shell 脚本时，就会出现这个错误。


![](/data/attachment/album/202308/03/155023wrr6p3eavnpo9rzf.png)


请注意，该退出码只出现在没有足够权限的脚本或命令的“*执行*”中，这与一般的**权限被拒绝**错误不同。


因此，不要把它与你之前看到的退出码为 `2` 的示例混淆。在那个示例中，运行的是 `ls` 命令，权限问题出自它试图执行的目录。而本例中权限问题来自脚本本身。


### 退出码 127


这是另一个常见的退出码。退出码 `127` 指的是“[未找到命令](https://itsfoss.com/bash-command-not-found/)”。它通常发生在执行的命令有错别字或所需的可执行文件不在 `$PATH` 变量中时。


例如，当我尝试执行一个不带路径的脚本时，经常会看到这个错误。


![Script executed without the path gives "command not found" or code 127](/data/attachment/album/202308/03/155023gh6oj2udz7b3m67m.png)


当你想运行的可执行文件不在 `$PATH` 变量中时，也会出现退出码 `127`。你可以通过 [在 PATH 变量中添加命令的目录](https://itsfoss.com/add-directory-to-path-linux/) 来纠正这种情况。


当你输入不存在的命令时，也会得到这样的退出码。


![Unmount is not a command, and Screenfetch is not installed, which resulted in code 127](/data/attachment/album/202308/03/155023bhg73244v2rg4hwk.png)


### 退出码 128+n 系列


当应用程序或命令因致命错误而终止或执行失败时，将产生 128 系列退出码（`128+n`），其中 `n` 为信号编号。


`n` 包括所有类型的终止代码，如 `SIGTERM`、`SIGKILL` 等。


#### 退出码 130 或 SIGINT


在通过终止信号 `2` 或按下 `Ctrl+C` 中断进程时，会发出 `SIGINT`（键盘中断信号）。


因为终止信号是 `2`，所以我们得到的退出码是 `130`（128+2）。下面的视频演示了 `lxappearance` 的中断信号。






#### 退出码 137 或 SIGKILL


`SIGKILL`（立即终止信号）表示终止信号 `9`。这是终止应用程序时最不应该使用的方法。


因为终止信号为 `9`，因此我们得到的退出代码为 `137`（128+9）。






#### 退出码 143 或 SIGTERM


`SIGTERM` 是进程在未指定参数的情况下被杀死时的默认行为。


`SIGTERM` 的终止信号为 `15`，因此该信号的退出码为 `143`（128+15）。






还有一些你以前可能不知道的终止信号，它们也有自己类似的退出码。你可以在这里查看它们：



> 
> ? 请注意，如果进程在启动它的同一会话中终止，这些信号可能不会出现。如果要重现这些信号，请从不同的 shell 终止。
> 
> 
> 就个人而言，信号 `128` 是无法重现的。
> 
> 
> 


### 当退出码超过了 255 会怎样?


最新版本的 Bash 甚至保留了超过 255 的原始退出码的值，但一般来说，如果代码超过 255，就会被重新计算。


也就是说，代码 `256` 会变成 `0`，`257` 会变成 `1`，`383` 会变成 `127`，以此类推。为确保更好的兼容性，请将退出码保持在 `0` 至 `255` 之间。


### 结语


希望你对 Linux Shell 中的退出码有所了解。在排查各种问题时，使用它们会非常方便。


如果你要在 Shell 脚本中使用这些代码，请确保你了解每个代码的含义，以便更容易地排除故障。


这就是本文的全部内容。如有遗漏，请在评论区告诉我。


*（题图：MJ/719ff711-1b9f-4aa9-a82e-980704acbdd8）*




---


via: <https://itsfoss.com/linux-exit-codes/>


作者：[Pranav Krishna](https://itsfoss.com/author/pranav/) 选题：[lkxed](https://github.com/lkxed/) 译者：[lxbwolf](https://github.com/lxbwolf) 校对：[wxy](https://github.com/wxy)


本文由 [LCTT](https://github.com/LCTT/TranslateProject) 原创编译，[Linux中国](https://linux.cn/) 荣誉推出


OK
![Warp Terminal](/assets/images/warp-terminal.webp)


![Warp Terminal](/assets/images/warp-terminal.webp)

An exit code or exit status tells us about the status of the last executed command. Whether the command was completed successfully or ended with an error. This is obtained after the command terminates.

**The basic ideology is that programs return the exit code 0 to indicate that it executed successfully without issues. Code 1 or anything other than 0 is considered unsuccessful. **


There are many more exit codes other than 0 and 1, which I'll cover in this article.

## Various exit codes in Linux shell

Let us take a quick look at the prominent exit codes in the Linux shell:

Exit code | Meaning of the code |
---|---|

`0` |
Command executed with no errors |

`1` |
Code for generic errors |

`2` |
Incorrect command (or argument) usage |

`126` |
Permission denied (or) unable to execute |

`127` |
Command not found, or PATH error |

`128+n` |
Command terminated externally by passing signals, or it encountered a fatal error |

`130` |
Termination by Ctrl+C or SIGINT (termination code 2 or keyboard interrupt) |

`143` |
Termination by SIGTERM (default termination) |

`255/*` |
Exit code exceeded the range 0-255, hence wrapped up |


The termination signals like `130`

(SIGINT or `^C`

) and `143`

(SIGTERM) are prominent, which are just `128+n`

signals with `n`

standing for the termination code.

Now that you are briefly familiar with the exit codes let's see about their usage.

## Retrieving the exit code

The exit code of the previously executed command is stored in the [special variable](https://linuxhandbook.com/bash-special-variables/) `$?`

. You can retrieve the exit status by running:

`echo $?`


This will be used in all our demonstrations to retrieve the exit code.

Note that the *exit* command supports carrying the same exit code of the previous command executed.

## Exit code 0

Exit code `0`

means that the command is executed without errors. This is ideally the best case for the completion of commands.

For example, let us run a basic command like this

```
neofetch
echo $?
```


![](https://itsfoss.com/content/images/2023/06/exit_code_0.png)

This exit code `0`

means that the particular command was executed successfully, nothing more or less. Let us demonstrate some more examples.

You may try [killing a process](https://itsfoss.com/how-to-find-the-process-id-of-a-program-and-kill-it-quick-tip/); it will also return the code `0`

.

`pkill lxappearance`


![](https://itsfoss.com/content/images/2023/06/exit_code_0.gif)

Viewing a file's contents will also return an exit code 0, which implies **only** that the 'cat' command executed successfully.

## Exit code 1

Exit code `1`

is also a common one. It generally means the command terminated with a generic error.

For example, using the [package manager](https://itsfoss.com/package-manager/) without sudo permissions results in code 1. In Arch Linux, if I try this:

`pacman -Sy `


It will give me exist code as 1 meaning the last command resulted in error.

![exit code 1 (impermissible operation resulted in this code)](https://itsfoss.com/content/images/2023/06/exit_code_1.png)

If you try this in Ubuntu-based distros (`apt update`

without sudo), you get 100 as an error code for running 'apt' without permissions. This is not a standardized error code, but one specific to apt.

While this is a general understanding, we can also interpret this as "operation impermissible".

Operations like dividing by zero also result in code 1.

![Division by zero results in code 1](https://itsfoss.com/content/images/2023/06/exit_code_1-division_by_0-.png)

## Exit code 2

This exit code is given out when the command executed has a syntax error. Misusing the arguments of commands also results in this error.

It generally suggests that the command could not execute due to incorrect usage.

For example, I added two hyphens to an option that's supposed to have one hyphen. Code 2 was given out.

`grep --z file.txt`


![Invalid argument resulted in exit code 2](https://itsfoss.com/content/images/2023/06/exit_status_2-misusing_arguments--1.png)

When permission is denied, like accessing the /root folder, you get error code 2.

![Permission denied gives out code 2](https://itsfoss.com/content/images/2023/06/exit_code_2-permission_denied-.png)

## Exit code 126

126 is a peculiar exit code since it is used to indicate a command or script was not executed due to a permission error.

This error can be found when you try executing a shell script without giving execution permissions.

![](https://itsfoss.com/content/images/2023/06/exit_code_126.png)

Note that this exit code appears only for the '*execution*' of scripts/commands without sufficient permissions, which is different from a generic Permission Denied error.

So, on't confuse it with the previous example you saw with exit code 2. There, ls command ran and the permission issue came with the directory it was trying to execute. Here, the permission issues came from the script itself.

## Exit code 127

This is another common one. Exit code 127 refers to "[command not found](https://itsfoss.com/bash-command-not-found/)". It usually occurs when there's a typo in the command executed or the required executable is not in the $PATH variable.

For example, I often see this error when I try executing a script without its path.

![Script executed without the path gives "command not found" or code 127](https://itsfoss.com/content/images/2023/06/exit_code_127.png)

Or when the executable file you're trying to run, is not listed in the `$PATH`

variable. You can rectify this by [adding the parent directory to the PATH variable](https://itsfoss.com/add-directory-to-path-linux/).

[How to Add a Directory to PATH in LinuxLearn all the essential steps about adding a directory to the PATH in Linux and making those changes permanently.](https://itsfoss.com/add-directory-to-path-linux/)![](https://itsfoss.com/content/images/wordpress/2021/05/set-up-path-linux.png)


![](https://itsfoss.com/content/images/wordpress/2021/05/set-up-path-linux.png)

You'll also get this exit code when you type commands that do not exist.

![Unmount is not a command, and Screenfetch is not installed, which resulted in code 127](https://itsfoss.com/content/images/2023/06/exit_code_127-command_not_found--1.png)

*is not a command, and*

*Unmount**is not installed*

*Screenfetch*## Exit code series 128+n

When an application or command is terminated or its execution fails due to a fatal error, the adjacent code to 128 is produced (128+n), where n is the signal number.

This includes all types of termination codes, like `SIGTERM`

, `SIGKILL`

, etc that apply to the value 'n' here.

### Code 130 or SIGINT

`SIGINT`

or **Sig**nal for Keyboard ** Int**errupt is induced by interrupting the process by termination signal 2, or by Ctrl+C.

Since the termination signal is 2, we get a code 130 (128+2). Here's a video demonstrating the interrupt signal for `lxappearance`

.

SIGINT(2) termination or Keyboard Interrupt (^C) that gives code 130

### Code 137 or SIGKILL

The `SIGKILL`

termination **sig**nal that **kill**s the process instantly has a termination signal 9. This is the last method one should use while terminating an application.

The exit code thrown is 137 since the termination signal is 9 (128+9).

SIGKILL(9) termination that gives code 137

### Code 143 or SIGTERM

`SIGTERM`

or **Sig**nal to **Term**inate is the default behavior when a process is killed without specifying arguments.

The termination code for SIGTERM is 15, hence this signal gets an exit code of 143 (128+15).

SIGTERM(15) termination that gives code 143

There are other termination signals that you may not have known before; they too have their own exit codes similar to these. You can check them out here:

[How to use SIGINT and other Termination Signals in LinuxTerminating executing process is more than just kill -9. Here are some of the prominent termination signals and their usage.](https://linuxhandbook.com/termination-signals/)![](https://linuxhandbook.com/content/images/2022/10/termination-signals-linux.png)


![](https://linuxhandbook.com/content/images/2022/10/termination-signals-linux.png)

Note that these signals may not appear if terminated from the same session from which the process was started. If you're reproducing these, terminate from a different shell.

On a personal note, signal 128 was impossible to reproduce.

## What if the code exceeds 255?

Recent versions of Bash retain the original exit code value even beyond 255, but generally, if the code exceeds 255, then it is wrapped up.

That is, code 256 becomes '0', 257 becomes '1', 383 becomes '127', and so on and so forth. To ensure better compatibility, keep the exit codes between 0 and 255.

## Wrapping up

I hope you learned something about the exit codes in the Linux shell. Using them can come in handy for troubleshooting various issues.

If you are using these codes in a shell script, make sure you understand the meaning of each code in order to make it easier for troubleshooting.

In case you need a reference, check out the Bash series here:

[Bash Basics #1: Create and Run Your First Bash Shell ScriptStart learning bash scripting with this new series. Create and run your first bash shell script in the first chapter.](https://itsfoss.com/create-bash-script/)![](https://itsfoss.com/content/images/2023/06/Bash-script-hello-world.png)


![](https://itsfoss.com/content/images/2023/06/Bash-script-hello-world.png)

That's all about the article. Feel free to let me know in the comments section if I have missed anything.