退出运行脚本而不退出外壳

时间:2018-09-18 09:29:01

标签: bash ubuntu

我有一个脚本库,如果发生某些情况,它会使用许多exit命令。每次遇到出口时,外壳都会关闭。

关于这个问题,我看到了很多建议修改脚本的答案,但是我的脚本是第三方的,我认为作者并不意味着应该关闭外壳,所以我认为还有其他运行方式。

如何运行这些脚本,以便仅脚本停止,而外壳保持打开状态。目前,我使用. script.sh

2 个答案:

答案 0 :(得分:3)

您可以将脚本. script.sh启动为bash script.sh,而不用启动脚本。当您使用bash启动它时,将打开bash的子进程,并且您的脚本将在子shell中执行,而exit语句将使子shell关闭,并且没有父shell或主shell的作用域。

答案 1 :(得分:1)

如果您正在采购脚本库,并且想要使用脚本库定义的所有功能而不导致外壳退出,请使用嵌套子外壳。

示例:

# script.sh contents
hello_exit() { 
    echo "hello"; 
    sleep 1; 
    exit 10; 
}

# YOUR SHELL
source script.sh

# Use subshell
(hello_exit)

# If you want to capture the output and error code
output=$(hello_exit)
rc=$?