代码之家  ›  专栏  ›  技术社区  ›  notacorn

如何在bash脚本之前获取命令run的返回代码?

  •  0
  • notacorn  · 技术社区  · 11 月前
    $ beep; echo $?
    
    Command 'beep' not found, but can be installed with:
    
    apt install beep
    Please ask your administrator.
    
    127
    
    $ cat test.sh
    #!/usr/bin/env bash
    echo $?
    

    我的脚本的预期输出应该是“127”。

    那么,为什么以同样的方式执行bash脚本后,打印的返回代码不是我们所期望的?

    $ beep; ./test.sh
    
    Command 'beep' not found, but can be installed with:
    
    apt install beep
    Please ask your administrator.
    
    0
    
    1 回复  |  直到 11 月前
        1
  •  3
  •   Barmar    11 月前

    $? 不会被子进程继承。

    您可以将其导出到环境变量,并在脚本中检查。

    test.sh :

    #!/usr/bin/env bash
    echo $CODE
    

    然后

    beep
    CODE=$? ./test.sh
    

    或者你可以通过 $? 作为脚本参数:

    test.sh

    #!/usr/bin/env bash
    echo "$1"
    

    然后

    beep; ./test.sh $?
    
    推荐文章