Printing odd numbers in bash script giving error

Viewed 35438

Please tell why printing odd numbers in bash script with the following code gives the error:

line 3: {1 % 2 : syntax error: operand expected (error token is "{1 % 2 ")

for i in {1 to 99}
do
rem=$(( $i % 2 ))
if [$rem -neq 0];
then
echo $i
fi
done
8 Answers

Not really sure why nobody included it, but this works for me and is simpler than the other 'for' solutions:

for (( i = 1; i < 100; i=i+2 )); do echo $i ; done

One liner:

for odd in {1..99..2}; do echo "${odd}"; done

Or print in a cluster.

for odd in {1..99..2}; do echo -n " ${odd} "; done

Likewise, to print even numbers only:

for even in {2..100..2}; do echo "${even}"; done

OR

for even in {2..100..2}; do echo -n " ${even} "; done
for (( i=1; i<=100; i++ ))
do
    ((b = $i % 2))
  if [ $b -ne 0 ] 
    then
    echo $i
fi
done
for i in {1..99}
do
    rem=`expr $i % 2`
    if [ $rem == 1 ]
    then
        echo  "$i"
    fi
done
for i in {0..49}
do
 echo $(($i*2+1))
done
Related