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

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

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

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

然后运行。sh as

...
exit
...

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

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


当前回答

正如其他人注意到的那样,源脚本和执行脚本使用return和exit来保持相同的会话打开,这是正确的。

这里有一个相关的技巧,如果你想要一个脚本,应该保持会话打开,不管它是否来源。

下面的示例可以像foo.sh那样直接运行,也可以像。foo.sh / foo.sh来源。无论哪种方式,它都将在“退出”后保持会话打开。$@字符串被传递,这样函数就可以访问外部脚本的参数。

#!/bin/sh
foo(){
    read -p "Would you like to XYZ? (Y/N): " response;
    [ $response != 'y' ] && return 1;
    echo "XYZ complete (args $@).";
    return 0;
    echo "This line will never execute.";
}
foo "$@";

终端的结果:

foo.sh美元 你想要XYZ吗?(Y / N): N 美元。foo.sh 你想要XYZ吗?(Y / N): N $ | (终端窗口保持打开并接受额外输入)

这对于在单个终端中快速测试脚本更改非常有用,同时在您工作时在主退出/返回下保留一堆废弃代码。它还可以使代码在某种意义上更具可移植性(如果您有大量的脚本,这些脚本可能以不同的方式调用,也可能不以不同的方式调用),尽管只在适当的地方使用return和exit要简单得多。

其他回答

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

# 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'
}

“问题”实际上是您在获取脚本,而不是执行脚本。当您源文件时,其内容将在当前shell中执行,而不是生成子shell。所有东西,包括exit,都会影响当前shell。

与其使用exit,不如使用return。

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

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

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

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

您可以在return语句/命令之后添加一个额外的退出命令,这样它就可以同时从命令行执行脚本和从终端获取源。

脚本中的退出代码示例:

   if [ $# -lt 2 ]; then
     echo "Needs at least two arguments"
     return 1 2>/dev/null
     exit 1
   fi

当您在返回命令之后查找脚本时,将不会调用带有exit命令的行。

当您执行脚本时,返回命令会给出一个错误。因此,我们通过将错误消息转发到/dev/null.来抑制错误消息