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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 23:30:08  来源:igfitidea点击:

How do I check whether a variable has an even numeric value?

bash

提问by lizarisk

How should I change this to check whether valhas 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 bashexpects a command.

$(( ... ))只是一种表达。它的结果出现在bash需要命令的地方。

A POSIX-compatible solution would be:

POSIX 兼容的解决方案是:

if [ "$(( RANDOM % 2))" -ne 0 ]; 

but since RANDOMisn't defined in POSIX either, you may as well use the right bashcommand for the job: an arithmetic evaluation compound command:

但由于RANDOM也没有在 POSIX 中定义,您也可以使用正确的bash命令来完成这项工作:算术评估复合命令:

if (( RANDOM % 2 )); then