bash 如何检查变量是否具有偶数值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15659848/
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 do I check whether a variable has an even numeric value?
提问by lizarisk
How should I change this to check whether val
has an even or odd numeric value?
我应该如何更改它以检查是否val
具有偶数或奇数数值?
val=2
if $((RANDOM % $val)); ...
回答by Fredrik Pihl
$ a=4
$ [ $((a%2)) -eq 0 ] && echo "even"
even
$ a=3
$ [ $((a%2)) -eq 0 ] && echo "even"
回答by Paul
foo=6
if [ $((foo%2)) -eq 0 ];
then
echo "even";
else
echo "odd";
fi
回答by chepner
$(( ... ))
is just an expression. Its result appears where bash
expects a command.
$(( ... ))
只是一种表达。它的结果出现在bash
需要命令的地方。
A POSIX-compatible solution would be:
POSIX 兼容的解决方案是:
if [ "$(( RANDOM % 2))" -ne 0 ];
but since RANDOM
isn't defined in POSIX either, you may as well use the right bash
command for the job: an arithmetic evaluation compound command:
但由于RANDOM
也没有在 POSIX 中定义,您也可以使用正确的bash
命令来完成这项工作:算术评估复合命令:
if (( RANDOM % 2 )); then