如何在(否定)Bash 条件中使用 OR
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7376058/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to use OR within (negative) Bash conditions
提问by octosquidopus
This section of my script checks whether the distro is either Ubuntu or Arch. The problem is that I cannot figure out what to replace the ORwith to make it work. I tried -oand other suggestions from various websites without succes.
我脚本的这一部分检查发行版是 Ubuntu 还是 Arch。问题是我无法弄清楚用什么来替换OR以使其工作。我尝试-o了各种网站的其他建议,但没有成功。
if [ ! $(lsb_release -is) == "Ubuntu" OR "Arch" ]; then
echo "Neither Ubuntu nor Arch!"
read -p "Continue anyway(y/N)? "
sleep 0
[ "$REPLY" == "y" ] || exit
fi
回答by paxdiablo
You can use something like:
你可以使用类似的东西:
rel="$(lsb_release -is)"
if [[ "${rel}" != "Ubuntu" && "${rel}" != "Arch" ]]; then
# Neither Ubuntu nor Arch
fi
回答by bash-o-logist
Use a case/esacconstruct
使用case/esac构造
case $(lsb_release -is) in
Ubuntu|Arch ) echo "Ubuntu or Arch found";;
* )
echo "Neither Ubuntu nor Arch!"
read -p "Continue anyway(y/N)? "
sleep 0
[ "$REPLY" == "y" ] || exit
;;
esac
回答by Sorin
Closest to your original code would be:
最接近您的原始代码是:
if [[ ! $(lsb_release -is) =~ Ubuntu|Arch ]]; then
echo "Neither Ubuntu nor Arch!"
read -p "Continue anyway(y/N)? "
sleep 0
[ "$REPLY" == "y" ] || exit;
fi
This uses the match operator introduced in bash 3. Also note that the above is valid in bash 3.2, prior to that you need to use quotes for the pattern.
这使用了 bash 3 中引入的匹配运算符。另外请注意,上述内容在 bash 3.2 中有效,在此之前您需要为模式使用引号。
if you don't have bash 3 you can use grep
如果你没有 bash 3 你可以使用 grep
if ! lsb_release -is| egrep -q 'Ubuntu|Arch'; then
echo "Neither Ubuntu nor Arch!"
read -p "Continue anyway(y/N)? "
sleep 0
[ "$REPLY" == "y" ] || exit;
fi
Note that -q is a non-standard option of grep
注意 -q 是 grep 的非标准选项
回答by octosquidopus
To answer my own question, here is a slightly longer but more flexible way of achieving the same result.
为了回答我自己的问题,这里有一个稍长但更灵活的方法来实现相同的结果。
rel="$(lsb_release -is)"
if [[ "${rel}" = "Arch" ]]; then
echo "It's Arch"
elif [[ "${rel}" = "Ubuntu" ]]; then
echo "It's Ubuntu"
else
echo "It's Neither"
read -p "Continue anyway(y/N)? "
sleep 0
[ "$REPLY" == "y" ] || exit
fi

