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

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

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

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

然后运行。sh as

...
exit
...

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

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


当前回答

如果命令成功执行,则返回值为0。之后我们可以检查它的返回值。

bash中是否有“goto”语句?

这里有一些肮脏的工作方法,使用陷阱只向后跳。


#!/bin/bash
set -eu
trap 'echo "E: failed with exitcode $?" 1>&2' ERR

my_function () {
    if git rev-parse --is-inside-work-tree > /dev/null 2>&1; then
        echo "this is run"
        return 0
    else
        echo "fatal: not a git repository (or any of the parent directories): .git"
        goto trap 2> /dev/null
    fi
}

my_function
echo "Command succeeded"  # If my_function failed this line is not printed

相关:

https://stackoverflow.com/a/19091823/2402577 如何使用$?并测试检查功能?

其他回答

我也遇到了同样的问题,根据上面的答案和我的理解,最终对我有用的是:

有一个shebang行来调用预期的脚本,例如, # !/bin/bash使用bash执行脚本

我有两种shebang的脚本。因此,使用sh或。不可靠,因为它会导致错误执行(比如当脚本运行不完全时退出)

因此,答案是

确保脚本有一个shebang,这样就不会对其预期的处理程序产生疑问。 Chmod .sh文件以便执行。(chmod +x file.sh) 直接调用它,不需要任何sh或。 (. / myscript.sh)

希望这对有类似问题的人有所帮助。

要编写一个既可以作为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 ....."

我找不到解决方案,所以对于那些想要离开嵌套脚本而不离开终端窗口的人:

# this is just script which goes to directory if path satisfies regex
wpr(){
    leave=false
    pwd=$(pwd)
    if [[ "$pwd" =~ ddev.*web ]]; then
        # echo "your in wordpress instalation"
        wpDir=$(echo "$pwd" | grep -o  '.*\/web')
        cd $wpDir
        return
    fi
    echo 'please be in wordpress directory'
    # to leave from outside the scope
    leave=true
    return
}

wpt(){
    # nested function which returns $leave variable
    wpr
    
    # interupts the script if $leave is true
    if $leave; then
        return;
    fi
    echo 'here is the rest of the script, executes if leave is not defined'
}

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

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

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

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

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

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