Search code examples
bashloopsshellfor-loopstep-through

How to print every 17th number, 0-200, skipping even numbers?


I need to write a Bash/Shell code that prints every 17th number from 0 to 200, skipping all even numbers.

This is the code I have right now (I know it doesn't work as intended):

for i in {0..200..17}
do
if [ $(($i % 2)) ]
then
  echo -n "${i}, "
fi
done;

I need to print an output that looks like this:

17, 51, 85, 119, 153, 187

I have the part where it steps through every 17th number, but I can't seem to figure out how to get it to skip every even number and every guide I've read through online doesn't help. Appreciation in advance!


Solution

  • Change [ $(($i % 2)) ] into (( i % 2 )) so you're simply doing an arithmetic operation and testing the result (success=0/fail=non-zero exit status) rather than an arithmetic operation and then testing the output of that operation.

    Output:

    $ echo $((27 % 2))
    1
    
    $ echo $((26 % 2))
    0
    

    Exit status:

    $ ((27 % 2)); echo $?
    0
    
    $ ((26 % 2)); echo $?
    1