简体   繁体   English

在不调用子shell的情况下捕获源shell脚本的退出代码

[英]Capturing the exit code of sourced shell script without invoking subshell

I have two shell scripts:我有两个shell脚本:

test.sh测试文件

function func() {
echo $1
exit 1
}

run.sh运行文件

source ./test.sh

func "Hello"
exitCode=$?
echo "Output: ${exitCode}"

Result:结果:

Hello

The current problem which I'm facing is that when the function func returns 1, my run.sh script breaks and nothing gets executed after it.我目前面临的问题是,当函数 func 返回 1 时,我的 run.sh 脚本会中断,之后没有任何内容被执行。 So, is there any way I can effectively capture the exit code without breaking run.sh.那么,有什么方法可以在不破坏 run.sh 的情况下有效地捕获退出代码。 I know there is way to invoke a subshell using ( func "Hello" ) but I want to do it without invoking sub-shell using flock.我知道有一种方法可以使用( func "Hello" )调用子外壳,但我想在不使用 flock 调用子外壳的情况下做到这一点。 I looked up for reference example but could'nt find any close to it.我查找了参考示例,但找不到任何接近的示例。

2 ideas that are "pushing the boundary". 2个“突破界限”的想法。 Use with care , as future changes to the sourced script(s) might break the logic.小心使用,因为未来对源脚本的更改可能会破坏逻辑。 Recommended only if there is a way to monitor that script is working OK - eg when executing interactively, etc.仅当有一种方法可以监控该脚本是否正常工作时才推荐 - 例如,当以交互方式执行时等。

I would not use this kind of solutions in any production/critical system.我不会在任何生产/关键系统中使用这种解决方案。

Option 1: Alias 'exit' to 'return' when sourcing the file.选项 1:在获取文件时将“退出”别名为“返回”。

Assuming that ALL 'exit' statement in the test.sh are to be replaced with 'return', and assuming that you are willing to take the risk of future changes to test.sh, consider using alias before sourcing假设 test.sh 中的所有 'exit' 语句都将被替换为 'return',并且假设您愿意承担将来更改 test.sh 的风险,请考虑在采购之前使用alias

alias exit=return
source test.sh
unalias exit
func "foo"

Option 2: automatically update the function that is using 'exit' to use return.选项 2:自动更新使用 'exit' 的函数以使用 return。

source test.sh
body=$(type func | tail +2 | sed -e 's/exit/return/g')
eval "$body"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM