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

前端 未结 3 728
走了就别回头了
走了就别回头了 2020-12-25 11:06

How should I change this to check whether val has an even or odd numeric value?

val=2
if $((RANDOM % $val)); ...
相关标签:
3条回答
  • 2020-12-25 11:19
    $ a=4
    
    $ [ $((a%2)) -eq 0 ] && echo "even"
    even
    
    $ a=3
    
    $ [ $((a%2)) -eq 0 ] && echo "even"
    
    0 讨论(0)
  • 2020-12-25 11:21
    foo=6
    
    if [ $((foo%2)) -eq 0 ];
    then
        echo "even";
    else
        echo "odd";
    fi
    
    0 讨论(0)
  • 2020-12-25 11:30

    $(( ... )) is just an expression. Its result appears where bash expects a command.

    A POSIX-compatible solution would be:

    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:

    if (( RANDOM % 2 )); then
    
    0 讨论(0)
提交回复
热议问题