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

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

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

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

然后运行。sh as

...
exit
...

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

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


当前回答

是的,你可以用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.

其他回答

实际上,我认为您可能对应该如何运行脚本感到困惑。

如果您使用sh来运行一个脚本,例如sh ./run2.sh,即使嵌入式脚本以exit结束,您的终端窗口仍然会保留。

但是如果你使用。或源,您的终端窗口将退出/关闭以及下标结束。

有关详细信息,请参阅使用sh和source的区别是什么?

如果你的终端模拟器没有-hold,你可以净化一个源脚本,并保持终端:

#!/bin/sh
sed "s/exit/return/g" script >/tmp/script
. /tmp/script
read

否则你可以使用$TERM -hold -e脚本

要编写一个既可以作为shell脚本运行,也可以作为rc文件源运行的脚本,该脚本可以检查和比较$0和$BASH_SOURCE,并确定是否可以安全地使用exit。

下面是一个简短的代码片段

[ "X$(basename $0)" = "X$(basename $BASH_SOURCE)" ] && \
    echo "***** executing $name_src as a shell script *****" || \
    echo "..... sourcing $name_src ....."

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

我认为这是因为您在源模式下运行它 带点的

. myscript.sh

你应该在子shell中运行它:

/full/path/to/script/myscript.sh

“源”http://ss64.com/bash/source.html