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
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
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
if ((i % 2 == 0)); then ...
Commented
Jun 23, 2021 at 18:27
for i in {1..100}; do (( i%2 )) && echo $i; done
seq 1 2 100
:-)for ((i=1; i<=100; i+=2))
in bash :-)