Bash 如何基于子函数返回值退出父函数?
当我运行此脚本并输入Bash 如何基于子函数返回值退出父函数?,bash,Bash,当我运行此脚本并输入y时,我想退出fun1并继续运行fun2 怎么做 提前谢谢 如何处理函数的返回值 #!/bin/bash #make your own choice,decide which function should be run set -e keyin(){ read -e -p "$1 input y,otherwise input n" local yorn if [[ "y" == "$yorn" || "Y" == "$yorn" ]]; then
y
时,我想退出fun1
并继续运行fun2
怎么做
提前谢谢 如何处理函数的返回值
#!/bin/bash
#make your own choice,decide which function should be run
set -e
keyin(){
read -e -p "$1 input y,otherwise input n" local yorn
if [[ "y" == "$yorn" || "Y" == "$yorn" ]]; then
return 0
fi
}
fun1(){
keyin 'update software no.1'
echo 'how to exit this function?'
}
fun2(){
keyin 'update software no.2'
echo "fun2 is still running"
}
fun1
fun2
简单的if函数;然后,让我们根据函数的返回值是零还是非零来执行操作
语句<代码>读取。。。。本地yorn
读取名为local
的变量中的值。我想你的意思是读。。。。yorn没有本地
字。返回1
将退出整个脚本,因为set-e
语句已读。。。。本地yorn
读取名为yorn
的变量,local
表示本地变量。@kittygirl不,它不会<代码>设置-e在返回值为“未处理”时退出脚本。因此false
将退出脚本。但是如果为假;那是真的;否则是真的;fi
不会,因为语句if返回真值。if;然后fi
被解析为set-e
的一条语句。if
的返回值是执行的最后一个命令,因此if true;然后是假的;fi
仍将退出脚本。@kittygirl不,它不会。read.中的字符串local
。。本地
被解释为变量名。你想要localyorn;阅读约恩
。
keyin() {
# read -e -p "$1 input y,otherwise input n" local yorn
yorn=n
if [[ "y" == "$yorn" || "Y" == "$yorn" ]]; then
return 0
fi
return 1 # return nonzero in case of error
}
fun1() {
# handle the return value - in case of non-zero execute custom action
if ! keyin 'update software no.1'; then
return
fi
echo 'how to exit this function?'
}
fun2() {
echo "fun2 is still running"
}
fun1
fun2