[英]How can I stop execution of a bash script, whether or not it's invoked with “source”?
我试图摆脱bash脚本中的退出调用,以使其可源。
此时脚本包含一个exit
,如果你正常调用脚本就可以了,但如果你输出它,它也会停止执行不需要的调用脚本。
如果我用return
替换exit
它将在源时很好地工作但是当它没有来源时它将失败并出现错误。
return: can only `return' from a function or sourced script
我正在寻找一个可以解决这两种情况的解决方案。
您可以将脚本的代码包装在一个函数中,然后可以从该函数return
。
__main() {
unset -f __main
...
if whatever; then
return
fi
...
}
__main "$@"
尝试return
,如果失败则退回exit
。
{ retval=$?; return "$retval" 2>/dev/null || exit "$retval"; }
测试如下:
cat >one <<'EOF'
#!/usr/bin/env bash
echo "one starting"
source two
echo "one ending"
EOF
cat >two <<'EOF'
#!/usr/bin/env bash
echo "two starting"
echo "two attempting to exit"
{ retval=$?; return "$retval" 2>/dev/null || exit "$retval"; }
echo "two still running after attempted exit
EOF
source one
......正确/正确地发出:
one starting
two starting
two attempting to exit
one ending
...而运行chmod +x two; ./two
chmod +x two; ./two
发出:
two starting
two attempting to exit
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.