当我在shell脚本中使用exit命令时,脚本将终止终端(提示符)。是否有办法终止一个脚本,然后留在终端?

我的脚本run.sh希望通过直接获取或者从另一个脚本获取来执行。

编辑: 更具体地说,有两个脚本run2.sh as

...
. run.sh
echo "place A"
...

然后运行。sh as

...
exit
...

当我经过它的时候。如果它在run.sh中命中退出代码线,我希望它停止到终端并停留在那里。但是使用出口,整个航站楼会关闭。

PS:我已经尝试使用返回,但回声代码线仍将执行....


当前回答

而不是运行脚本使用。您可以使用sh Run2.sh或bash Run2.sh运行它

将启动一个新的子shell,然后运行脚本,它将在脚本结束时关闭,而打开另一个shell。

其他回答

1)如果脚本成功,exit 0将从脚本中出来。

2)如果失败,exit 1将从脚本中出来。

你可以根据你的需要尝试以上两种。

是的,你可以用return代替exit。它的主要目的是从shell函数返回,但如果在source-d脚本中使用它,它将从该脚本返回。

如Bash参考手册§4.1“Bourne Shell Builtins”所述:

return [n] Cause a shell function to exit with the return value n. If n is not supplied, the return value is the exit status of the last command executed in the function. This may also be used to terminate execution of a script being executed with the . (or source) builtin, returning either n or the exit status of the last command executed within the script as the exit status of the script. Any command associated with the RETURN trap is executed before execution resumes after the function or script. The return status is non-zero if return is used outside a function and not during the execution of a script by . or source.

这就像在脚本run2.sh中放入一个运行函数一样。 您可以在run中使用退出代码,同时在bash tty中生成run2.sh文件。 如果给运行函数退出脚本的权力,并给run2.sh 它是退出终结者的力量。 然后因为运行函数有能力退出你的终止器。

    #! /bin/sh
    # use . run2.sh

    run()
    {
        echo "this is run"
        #return 0
        exit 0
    }

    echo "this is begin"
    run
    echo "this is end"

不管怎样,我同意卡兹的观点,这是一个设计问题。

改进Tzunghsing的答案,有更清晰的结果和错误重定向,用于无声使用:

#!/usr/bin/env bash

echo -e "Testing..."

if [ "X$(basename $0 2>/dev/null)" = "X$(basename $BASH_SOURCE)" ]; then
    echo "***** You are Executing $0 in a sub-shell."
    exit 0
else
    echo "..... You are Sourcing $BASH_SOURCE in this terminal shell."
    return 0
fi

echo "This should never be seen!"

或者如果你想把这个放进一个静默函数:

function sExit() {
    # Safe Exit from script, not closing shell.
    [ "X$(basename $0 2>/dev/null)" = "X$(basename $BASH_SOURCE)" ] && exit 0 || return 0
}

...

# ..it have to be called with an error check, like this: 
sExit && return 0

echo "This should never be seen!"

请注意:

如果你在脚本中启用了erreexit (set -e),并且返回N且N != 0,你的整个脚本将立即退出。要查看所有shell设置,请使用,set -o。 在函数中使用时,第一个返回0表示退出函数,第二个返回0表示退出脚本。

还要确保返回时带有预期的返回值。否则,如果你在遇到退出时使用exit,它将从你的base shell退出,因为source没有创建另一个进程(实例)。