我如何停止执行bash脚本,无论是否用“源”调用它?

时间:2018-10-29 17:41:18

标签: bash

我正在尝试摆脱bash脚本中的退出调用,以使其可获取。

此刻,脚本包含一个exit,如果您正常调用该脚本可以,但是如果您获取它,它也会停止执行不需要的调用脚本。

如果我将exit替换为return,它将在来源时很好地工作,但是在未来源时会失败,并显示错误。

return: can only `return' from a function or sourced script

我正在寻找一种适用于两种情况的解决方案。

2 个答案:

答案 0 :(得分:2)

您可以将脚本的代码包装在一个函数中,然后可以从中return开始使用

__main() {
    unset -f __main

    ...
    if whatever; then
        return
    fi
    ...
}

__main "$@"

答案 1 :(得分:1)

尝试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会发出:

two starting
two attempting to exit