在Linux 系统中,每当命令执行完成后,系统都会返回一个退出状态。该退出状态用一整数值表示,用于判断命令运行正确与否。若退出状态值为 0,表示命令运行成功;而退出状态值不为 0时,则表示命令运行失败。最后一次执行的命令的退出状态值被保存在内置变量“ $?”中,所以可以通过echo语句进行测试命令是否运行成功。 POSIX规定了以下几种退出状态和退出状态的含义。
常用参数
格式:exit n
退出。设置退出码为n。(Cause the shell to exit with a status of n.)
格式:exit
退出。退出码不变,即为最后一个命令的退出码。(If n is omitted, the exit status is that of the last command executed. )
格式:$?
上一个命令的退出码。
格式:trap "commands" EXIT
退出时执行commands指定的命令。( A trap on EXIT is executed before the shell terminates.)
退出码(exit status,或exit code)的约定:
0表示成功(Zero - Success)
非0表示失败(Non-Zero - Failure)
2表示用法不当(Incorrect Usage)
127表示命令没有找到(Command Not Found)
126表示不是可执行的(Not an executable)
使用示例
示例一 退出当前shell
[root@new55 ~]# [root@new55 ~]# exit logout
示例二 在脚本中,进入脚本所在目录,否则退出
Bash代码
1 |
|
示例三 在脚本中,判断参数数量,不匹配就打印使用方式,退出
1 2 3 4 |
|
示例四 在脚本中,退出时删除临时文件
1 |
|
示例五 检查上一命令的退出码
1 2 3 4 5 |
|
以下是一些实际的例子:
alloy@raspberrypi:/home$ ls
alloy pi
alloy@raspberrypi:/home$ echo $?
0
#运行成功
alloy@raspberrypi:/home$ ls test
ls: cannot access test: No such file or directory
alloy@raspberrypi:/home$ echo $?
2
#传递参数失败
alloy@raspberrypi:/home$ test
alloy@raspberrypi:/home$ echo $?
1
#传递参数失败
alloy@raspberrypi:/home$ alloy
-bash: alloy: command not found
alloy@raspberrypi:/home$ echo $?
127
#没有这个命令
---------------------
作者:alloy
来源:CSDN
原文:https://blog.csdn.net/alloyinrunning/article/details/23660265
https://www.cnblogs.com/itcomputer/p/4157859.html
版权声明:本文为博主原创文章,转载请附上博文链接!
附加阅读:
ubuntu运行sh脚本sudo自动输入密码
使用管道(上一个命令的 stdout 接到下一个命令的 stdin):
#!/bin/bash
echo password | sudo -S apt-get update
-S参数的作用
使用man命令查询sudo,对参数-S的说明