如果函数名用作shell脚本if-else语句中的表达式,那么表达式值是什么?
在以下shell脚本中,函数返回错误 失败后非零,但控件正在输入else语句。为什么呢?
#!/bin/sh
test_internet()
{
printf "Checking for internet connectivity : \t"
ping -c 4 -q www.google.com
retval=$?
echo $retval
if [ $retval != 0 ]
then
return "$retval"
fi
}
main()
{
if test_internet ; then
printf "test passed\n"
else
printf "failed\n"
fi
}
main
答案 0 :(得分:1)
if语句中的函数没什么特别的。调用该函数并将其返回值视为(零=真,非零=假)。
来自man 1 bash
:
if list; then list; [ elif list; then list; ] ... [ else list; ] fi
The if list is executed. If its exit status is zero, the then list is executed. Otherwise, each elif list is executed in turn, and if its exit status is zero, the corresponding then list is
executed and the command completes. Otherwise, the else list is executed, if present. The exit status is the exit status of the last command executed, or zero if no condition tested true.
因此,只需执行关键字if
之后,其返回值就会用于条件检查。
就像您通常会检查数字是否相等一样,您可以获得如下的可视化报告:
# if [ 1 -eq 2 ]; then do_something; fi
[ 1 -eq 2 ]; echo $?