将代码从子脚本退出到父脚本

时间:2021-03-11 15:06:10

标签: bash shell

我有以下调用子脚本的父脚本。

父.sh

#!/bin/bash
export home=`pwd`
echo "calling child"
. ${home}/bin/child.sh
retn_code=$?
if (retn_code -ne 0)
then
    exit $retn_code
else
    echo "successful"
fi
exit 0

child.sh:

#!/bin/bash
exit 1

当我执行父脚本时,父脚本中没有捕获 1 的退出状态。打印的日志最后一行是“calling child”,之后日志中没有打印任何行。

从孩子到父母的退出状态是否有遗漏?

1 个答案:

答案 0 :(得分:1)

. 不会调用子进程,而是运行其代码。因此,如果子脚本调用 exit,父脚本将退出。你想做:

#!/bin/bash
home=$(pwd)
echo "calling child"
if "${home}"/bin/child.sh; then
    echo success
else
    exit   # status returned by child will propagate
fi
exit 0

请注意,这里使用变量 home 很奇怪。如果你想在 child.sh 中定义它,IMO 写 if home=$(pwd) ./bin/child.sh; then ... 会更清楚。您对 export 的使用意味着您希望在 child.sh 中定义它,但我怀疑您实际上并不想要它。这与问题无关,所以我刚刚删除了我认为不必要的导出。