【发布时间】:2016-09-01 16:44:41
【问题描述】:
我有这个 bash 函数来检查我是否在互联网上。当我需要在 bash 脚本中进行快速 if internet-connected 测试时,它会有所帮助。
由于上个月它非常有用,我尝试复制它的设计以拥有一个简单的 ubuntu 测试器来测试操作系统是否是 Ubuntu。然后就发生了这样的事情……
test.sh
internet-connected(){
wget -q --spider http://google.com
if [ $? -eq 1 ]
then
echo 'internet is connected'
return 1
else
echo 'internet is not connected'
return 0
fi
}
echo "testing internet-connected"
if internet-connected
then
echo 'connected'
else
echo 'not connected'
fi
check-for-ubuntu(){
tester=$(lsb_release -i | grep -e "Ubuntu" -c)
if [ $tester -eq 1 ]
then
echo 'ubuntu detected'
return 1
else
echo 'ubuntu not detected'
return 0
fi
}
echo ""
echo "testing check-for-ubuntu"
if check-for-ubuntu
then
echo 'this is ubuntu'
else
echo 'this is not ubuntu'
fi
输出
testing internet-connected
internet is not connected
connected
testing check-for-ubuntu
ubuntu detected
this is not ubuntu
[Finished in 0.9s]
我的问题
为什么这两个函数的逻辑似乎倒退了?
你们回答得很好,谢谢。
【问题讨论】:
-
好问题,对我来说看起来很简单。调试 shell 脚本的标准第一步是将
set -x放在开头,这样您就可以看到所有命令的执行情况。 -
等待 - 两者都相同 - 在两者情况下,来自函数内部的消息与来自函数外部的消息相反。
-
我不确定我是否同意@Barmar 关于问题的质量——有很多与手头的问题无关的代码,因此违反了“M”(“最小”)部分MCVE.
-
@CharlesDuffy 我的意思是这是一个有趣的问题。而且我认为有两个测试用例进行比较会使示例更好 - 一个示例会是 too M.
-
@Barmar, ...当然,但不需要涉及外部代码。您可以摆脱
wget调用或lsb_release | ...并将它们替换为任何人都可以在任何 POSIX 机器上运行的常量true或false调用。
标签: linux bash shell ubuntu boolean-logic