在不退出终端的情况下停止 bashrc 执行

Stop bashrc execution on condition without exiting terminal

我有一个 .bashrc,我想看起来有点像这样:

testfunc() {
    if [ condition passes ] 
    then
        stop all execution
    fi
}

jobA() {
     testfunc
     ...
}

jobB() {
     testfunc
     ...
}

问题是如何在不退出终端的情况下停止所有执行?我知道只有两个选项可以停止执行:

  1. exit: 导致终端也被关闭
  2. return:它只停止执行 return 所在的函数。我可以让所有调用 testfunc 的函数检查它的 return 代码,但是有很多重复的 if 语句。

还有其他选择吗?

虽然检查 testfunc 的结果并不那么麻烦:testfunc || return 而不是你的 testfunc 是你所需要的(你不必拥有整个 if/then/fi).

关于你的问题...不,AFAIK 无法退出所有功能,但不能退出 shell 本身。

只需使用圆括号将您的作业放入子 shell 中。然后就可以退出sub shell.

$ type testfunc
testfunc is a function
testfunc () 
{ 
    if true; then
        exit;
    fi
}
$ type jobA
jobA is a function
jobA () 
{ 
    testfunc
}
$ type jobB
jobB is a function
jobB () 
{ 
    testfunc
}
$ ( jobA; jobB; )
$ 

并且终端不会退出。

如果将整个 .bashrc 代码包装在单个服务 while 循环中,您可以使用 break 将其保留:

#!/bin/bash                                                                     

# for testing
condition="true"

# a test func                                                                      
func() {
    if [ $condition == "true" ]
    then
        # 1 to break after calling, 0 not
        return 1
    fi
}
# the while    
while [ $((++i)) -eq 1 ]
# the main .bashrc code goes here
do
    # "exit" after a function
    func || break

    # or exit from main
    if [ $condition != "true" ]
    then
        break
    fi
done
# anything after the above done gets executed after break