bash - 你如何返回到源 bash 脚本?

标签 bash subprocess return exit

我在 bash 脚本中使用“source”,如下所示:

#!/bin/bash
source someneatscriptthatendsprematurely.sh

我想退出 someneatscriptthatendsprematurely.sh 脚本,而不退出主脚本。

感谢任何帮助!

最佳答案

您需要 return 语句:

return [n]

Causes a function to exit with the return value specified by n. If n is omitted, the return status is that of the last command executed in the function body. If used outside a function, but during execution of a script by the . (source) command, it causes the shell to stop executing that script and return either n or the exit status of the last command executed within the script as the exit status of the script. If used outside a function and not during execution of a script by ., the return status is false. Any command associated with the RETURN trap is executed before execution resumes after the function or script.

您可以使用以下两个脚本看到这一点:

script1.sh:
    . script2.sh
    echo hello again

script2.sh:
    echo hello
    return
    echo goodbye

当您运行 script1.sh 时,您会看到:

hello
hello again

关于bash - 你如何返回到源 bash 脚本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3666846/

相关文章:

linux - 为什么sed会匹配组外的东西作为组的一部分?

bash - wget 排除文件名列表

linux - 如何删除特定字符后的字符串中的所有内容?

C++ 不能返回变量

php - 在 PHP 中通过引用返回

bash - 如何在不转义的情况下grep星号?

python - Subprocess 语句在 python 控制台中有效,但在 Serverdensity 插件中无效?

python - 如何找到多个子流程的执行时间?

python 子进程不适用于 ssh 命令

php - 在 php 中, "return false"在 echo 语句之后有什么作用吗?