• linux退出状态码及exit命令


    Linux提供了一个专门的变量$?来保存上个已执行命令的退出状态码。对于需要进行检查的命令,必须在其运行完毕后立刻查看或使用$?变量。它的值会变成由shell所执行的最后一条命令的退出状态码:

    [root@host1 test]# date
    2017年 07月 19日 星期三 16:32:51 CST
    [root@host1 test]# echo $?
    0

    按照惯例,一个成功结束的命令的退出状态码是0。如果一个命令结束时有错误,退出状态码就是一个正数值(1-255):

    [root@host1 test]# qwert
    -bash: qwert: command not found
    [root@host1 test]# echo $?
    127

    无效命令会返回一个退出状态码127。Linux错误退出状态码没有什么标准可循,但有一些可用的参考,如下所示:

        Linux退出状态码
    状 态 码         描 述
    0          命令成功结束
    1          一般性未知错误
    2          不适合的shell命令
    126        命令不可执行
    127        没找到命令
    128        无效的退出参数
    128+x       与Linux信号x相关的严重错误
    130        通过Ctrl+C终止的命令
    255        正常范围之外的退出状态码

    退出状态码126表明用户没有执行命令的正确权限:

    [root@host1 test]# ./expect.sh
    -bash: ./expect.sh: 权限不够
    [root@host1 test]# echo $?
    126

    另一个会碰到的常见错误是给某个命令提供了无效参数:

    [root@host1 test]# cd %
    -bash: cd: %: 没有那个文件或目录
    [root@host1 test]# echo $?
    1

    这会产生一般性的退出状态码1,表明在命令中发生了未知错误。

    默认情况下,shell脚本会以脚本中的最后一个命令的退出状态码退出:

    [root@host1 test]# sh test.sh
    This is a test file
    [root@host1 test]# echo $?
    0

    你可以改变这种默认行为,返回自己的退出状态码。exit命令允许你在脚本结束时指定一个退出状态码:

    [root@host1 test]# cat test.sh
    #!/bin/bash
    A=10
    B=20
    C=$[$A + $B]
    echo the number is $C
    exit $C
    [root@host1 test]# sh test.sh 
    the number is 30
    [root@host1 test]# echo $?
    30

    这里直接使用了C的值为exit的退出值,也可以直接指定exit 30,这都是对的;但是你要注意这个功能,因为退出状态码最大只能是255。看下面例子中会怎样:

    [root@host1 test]# cat test.sh
    #!/bin/bash
    A=10
    B=30
    C=$[$A * $B]
    echo the number is $C
    exit $C
    [root@host1 test]# sh test.sh 
    the number is 300
    [root@host1 test]# echo $?
    44

    退出状态码被缩减到了0~255的区间,shell通过模运算得到这个结果。一个值的模就是被除后的余数。最终的结果是指定的数值除以256后得到的余数。在这个例子中,指定的值是300(返回值),余数是44,因此这个余数就成了最后的状态退出码。

  • 相关阅读:
    LeetCode 88. Merge Sorted Array
    LeetCode 75. Sort Colors
    LeetCode 581. Shortest Unsorted Continuous Subarray
    LeetCode 20. Valid Parentheses
    LeetCode 53. Maximum Subarray
    LeetCode 461. Hamming Distance
    LeetCode 448. Find All Numbers Disappeared in an Array
    LeetCode 976. Largest Perimeter Triangle
    LeetCode 1295. Find Numbers with Even Number of Digits
    如何自学并且系统学习计算机网络?(知乎问答)
  • 原文地址:https://www.cnblogs.com/01-single/p/7206664.html
Copyright © 2020-2023  润新知