Ubuntu 指令返回的结果查看/指令执行的退出状态/退出码查看

在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

cd $(dirname $0) || exit 1

 

示例三 在脚本中,判断参数数量,不匹配就打印使用方式,退出

1

2

3

4

if "$#" -ne "2" ]; then

    echo "usage: $0 <area> <hours>"

    exit 2

fi

示例四 在脚本中,退出时删除临时文件

1

trap "rm -f tmpfile; echo Bye." EXIT

示例五 检查上一命令的退出码

1

2

3

4

5

./mycommand.sh

EXCODE=$?

if "$EXCODE" == "0" ]; then

    echo "O.K"

fi

以下是一些实际的例子:

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的说明

 

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

或许,这就是梦想吧!

如果对你有用,欢迎打赏。

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值