gpt4 book ai didi

linux - shell中if条件中的函数名称

转载 作者:太空宇宙 更新时间:2023-11-04 04:55:13 26 4
gpt4 key购买 nike

如果函数名在 shell 脚本 if-else 语句中用作表达式,表达式的值是什么?

在下面的 shell 脚本中,after 函数在失败返回错误,该错误非零,但控件正在 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

最佳答案

if 语句中的函数没什么特别的。调用该函数并考虑其返回值(零 = true,非零 = false)。

来自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 $?

关于linux - shell中if条件中的函数名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48621959/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com