Bash:调用函数并检查返回值
我有一个这样的简单脚本:Bash:调用函数并检查返回值,bash,function,unix,Bash,Function,Unix,我有一个这样的简单脚本: #!/bin/bash main(){ test } test(){ local value=$(test2 "hi") if [ "$value" == "test hi" ]; then echo "function executed" fi } test2(){ echo "test2 executed" echo
#!/bin/bash
main(){
test
}
test(){
local value=$(test2 "hi")
if [ "$value" == "test hi" ];
then
echo "function executed"
fi
}
test2(){
echo "test2 executed"
echo "test $1"
}
main
基本上,我试图检查函数返回的值,并相应地控制执行。现在,当我执行此操作时,不会打印任何内容(甚至test2
函数中的echo
语句也不会打印)。但是,当我在test
函数(声明后)中添加echo$value
时,所有内容都会打印出来
是否有任何方法可以在不显式回显返回值的情况下处理test2返回的值。错误消息、调试输出、诊断、状态更新和进度信息应写入stderr
:
test2(){
echo "test2 executed" >&2
echo "test $1"
}
stdout
应专门用于函数的基本业务逻辑输出。通过这种方式,您可以捕获并通过管道传递值,而不会使其与调试消息混淆:
$ var=$(test2 "hi")
test2 executed
$ echo "The output from the function was <$var>"
The output from the function was <test hi>
$var=$(test2“hi”)
测试2已执行
$echo“函数的输出为”
函数的输出为
在函数中设置退出代码,并像其他条件一样进行检查
$: tst() { [[ foo == "$1" ]]; }
$: someVar=foo
$: if tst "$someVar"; then echo "arg was foo"; else echo "arg was NOT foo"; fi
arg was foo
$: someVar=bar
$: if tst "$someVar"; then echo "arg was foo"; else echo "arg was NOT foo"; fi
arg was NOT foo
默认情况下,任何函数的退出代码都是最后执行的命令的返回代码,除非您明确使用exit
或return
。(在函数中,它们是同义词。)
如果需要,可以创建更复杂的测试-
tst() {
case "$1" in
foo) return 0 ;;
bar) return 1 ;;
*) return -1 ;;
esac
}
tst "$someVar"
case "$?" in
0) echo "was foo" ;;
1) echo "was bar" ;;
*) echo "was unrecognized" ;;
esac
试试看。它返回的是test2 executed\ntest hi
,而不仅仅是test hi
。如果这不应该是返回值的一部分,请去掉echo“test2 executed”
。即使这样,它也不会在@BarmarIt执行:通过删除echo“test2 executed”对我也有效