2

I am learning Bash but I have some problems with printing the odd numbers in the range 1 to 100, obviously I have some syntax error which I cannot find.

for i in {1..100}
do
    if [ ($i % 2) -ne 0 ]
    then
        echo $i
    fi
done
9
  • for i in {1..100}; do (( i%2 )) && echo $i; done
    – anubhava
    Commented Jun 23, 2021 at 16:51
  • check how to use arithmetic expansion
    – jhnc
    Commented Jun 23, 2021 at 17:01
  • 1
    @anubhava seq 1 2 100 :-)
    – jhnc
    Commented Jun 23, 2021 at 17:04
  • 2
    @jhnc: Why use an external utility when we can use for ((i=1; i<=100; i+=2)) in bash :-)
    – anubhava
    Commented Jun 23, 2021 at 17:05
  • 1
    @jhnc indeed, I meant that (now fixed). I wasn't even trying to answer - I had noticed the first comment already did, I only wanted to point out that the OP asked about the syntax in his attempt, not so much about the best solution.
    – cornuz
    Commented Jun 23, 2021 at 17:25

2 Answers 2

13

The {x..y} construct allows a 3rd argument to designate the increment value (default is 1), eg:

for i in {1..20..3}    # start with 1 and increment by 3 until you reach/pass 20
do
    echo $i
done

This generates:

1
4
7
10
13
16
19

For odd vs even you designate the starting number and increment by 2:

# odd numbers

for i in {1..10..2}    # start with an odd number and increment by 2
do
    echo $i
done

1
3
5
7
9

# even numbers

for i in {2..10..2}    # start with an even number and increment by 2
do
    echo $i
done

2
4
6
8
10
1
  • 1
    No loop needed - printf "%s\n" {1..100..2} Commented Jun 23, 2021 at 18:13
1

I think your if statement isn't correct. Here's a small rewrite with a working if:

#!/bin/bash                                                                                                                                                                    
for i in {1..100}
do
    isEvenIfZero=$i%2;
    if [[ $isEvenIfZero -ne 0 ]];
    then
        #echo -n $i #single line
        echo $i
    fi
done
2
  • 2
    If you use the arithmetic conditional, you don't need the temp var: if ((i % 2 == 0)); then ... Commented Jun 23, 2021 at 18:27
  • The first echo has -n, which gets rid of the newline. You can get rid of the second echo by getting rid of the -n in the first echo. I like having all this on one line, but yeah, it's tighter without the second echo (I'll remove it)
    – user4280396
    Commented Jun 23, 2021 at 22:20

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.