如何从源脚本中获取退出代码

How to get the exit code from the source script

我有两个脚本主脚本和子脚本,我使用源脚本调用了子脚本,如果没有安装指定的包那么它应该 return 退出代码 1。

如果我 运行 使用主脚本 bash main.sh 我无法从主脚本中获取 subScriptExitCode

主脚本

source "sub.sh"

subScriptExitCode=$?

log "subScript ExitCode: $subScriptExitCode"

if [ $subScriptExitCode -ne 0 ]; then
    exit $subScriptExitCode
fi

子脚本

type -p <package>

subScriptExitCode=$?

if [ $subScriptExitCode -ne 0 ]; then
    exit 1
fi

而不是采购子脚本 运行 它如下所示并检查 return 代码

Main.sh

sh sub.sh

subScriptExitCode=$?

log "subScript ExitCode: $subScriptExitCode"

if [ $subScriptExitCode -ne 0 ]; then
    exit $subScriptExitCode
fi

获取文件时,请勿使用 exit,因为这会终止整个执行。相反,在 sub.sh 中使用 return :

return [n]

Causes a function to exit with the return value specified by n. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false.

sub.sh

type -p <package>

subScriptExitCode="$?"

if [ "$subScriptExitCode" -ne 0 ]; then
    return 1
fi

如果你看过 Bash 的手册,那么你就会阅读

source filename [arguments]: Read and execute commands from filename in the current shell environment and return the exit status of the last command executed from filename. If filename does not contain ...

source: man bash

这是与您的问题相关的两个非常重要的属性:

  1. 如果您的 sub_script 遇到一个不为零的 subScriptExitCode。由于 exit 语句,它将立即终止 main_script

  2. main_script 会将 subScriptExitCode 设置为 if 语句的退出状态。如果 sub_scriptsubScriuptExitCode 等于 0.

    ,则为零

    if list; then list; [ elif list; then list; ] ... [ else list; ] fi: ... The exit status is the exit status of the last command executed, or zero if no condition tested true.

    source: man bash

解决问题的一种可能方法是,仅使用 source 的属性:

sub_script:

type -p <package>
[ $? -eq 0 ]

此处,如果 type p <package> 以零结尾,测试命令将以状态 0 退出,否则 test-命令将以状态 1 退出。然后在您的 main_source 中将此状态拾取为 $?。但是,由于 type -p 只能 return 01,您可以去掉 test 并将 sub_script 减少为:

type -p <package>

type [-aftpP] name [name ...]: ... type returns true if all of the arguments are found, false if any are not found.

[source: man bash]