45

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

val=2
if $((RANDOM % $val)); ...
codeforester
  • 39,467
  • 16
  • 112
  • 140
lizarisk
  • 7,562
  • 10
  • 46
  • 70
  • What do you want to check? – fedorqui Mar 27 '13 at 13:20
  • I need this to be a correct conditional statement to check whether the random variable is even. Now it just says: "0: command not found" – lizarisk Mar 27 '13 at 13:22
  • Like this ? http://stackoverflow.com/questions/3601515/how-to-check-if-a-variable-is-set-in-bash – Brian Agnew Mar 27 '13 at 13:22
  • I just don't quite understand what am I doing wrong and what is the correct syntax. Square brackets around don't help either. – lizarisk Mar 27 '13 at 13:23
  • 4
    `if [ $(( $RANDOM % 2)) -eq 0 ]; then echo "even" ; fi` can work – fedorqui Mar 27 '13 at 13:24
  • 1
    Oh, I got it, should have left spaces around square brackets. – lizarisk Mar 27 '13 at 13:28
  • 1
    I believe the question here is - "Is the number even and not odd?" The answers here reflect this. There may be other questions that answer this. But the link used to mark the question duplicate is incorrect. That question answers if the variable is set. – shparekh Sep 16 '14 at 18:17
  • 1
    @Anthon the duplicate link is not related – user3132194 Mar 11 '16 at 06:16
  • 1
    This is *not* a duplicate of the question marked as a duplicate! *That* question regards whether a variable has had a value assigned to it (or if it exists), *this* question regards whether the numeric value of a variable is an even or odd number. I haven't checked the edits, but maybe the questioner clarified the question after first posting it? How do I mark something as falsely flagged? – Alex Hall Sep 15 '16 at 01:49

3 Answers3

67
$ a=4

$ [ $((a%2)) -eq 0 ] && echo "even"
even

$ a=3

$ [ $((a%2)) -eq 0 ] && echo "even"
Fredrik Pihl
  • 44,604
  • 7
  • 83
  • 130
44
foo=6

if [ $((foo%2)) -eq 0 ];
then
    echo "even";
else
    echo "odd";
fi
Paul
  • 20,883
  • 7
  • 57
  • 74
12

$(( ... )) 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
chepner
  • 497,756
  • 71
  • 530
  • 681
  • it is weird (ie, hard to read) that the `if (( RANDOM % 2 )); then` will be true when RANDOM is NOT a multiple of 2 ... – Olivier Dulac Mar 27 '13 at 13:37
  • This is the same idiom commonly used in other languages. C would have `if ( random/2 ) { ... }`. Python would have `if random/2: ...`. – chepner Mar 27 '13 at 13:40