为什么我的布尔测试在 bash 中切换?
Why did my boolean test switch in bash?
我有这个 bash 功能来检查我是否在互联网上。当我需要在 bash 脚本中进行快速 if internet-connected
测试时,它会有所帮助。
由于它在上个月非常有用,我尝试复制它的设计以获得一个简单的 ubuntu 测试器来测试 OS 是否为 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]
我的问题
为什么这两个函数看起来逻辑倒退了?
You guys answered this really well, thank you.
你的 check-for-ubuntu
可以这样使用 grep -q
:
check-for-ubuntu() {
lsb_release -i | grep -q "Ubuntu"
}
grep -q
将根据 lsb_release
命令中的模式 Ubuntu
return 1 或 0。
Shell 脚本不是 C(或 C++/Java/etc./etc./etc.)。
- 0 表示成功(真)。
- 任何其他表示错误(错误)。
您的 return 值是倒退的。
我有这个 bash 功能来检查我是否在互联网上。当我需要在 bash 脚本中进行快速 if internet-connected
测试时,它会有所帮助。
由于它在上个月非常有用,我尝试复制它的设计以获得一个简单的 ubuntu 测试器来测试 OS 是否为 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]
我的问题
为什么这两个函数看起来逻辑倒退了?
You guys answered this really well, thank you.
你的 check-for-ubuntu
可以这样使用 grep -q
:
check-for-ubuntu() {
lsb_release -i | grep -q "Ubuntu"
}
grep -q
将根据 lsb_release
命令中的模式 Ubuntu
return 1 或 0。
Shell 脚本不是 C(或 C++/Java/etc./etc./etc.)。
- 0 表示成功(真)。
- 任何其他表示错误(错误)。
您的 return 值是倒退的。