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

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

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

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

然后运行。sh as

...
exit
...

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

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


当前回答

你只需要用以下命令结束你的sh脚本:

bash

任何超出这个范围的事情都是你创造力的一部分。:)

其他回答

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

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

这就像在脚本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"

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

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

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

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

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

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

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

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

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

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