Reputation: 15
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!
Upvotes: 0
Views: 55
Reputation: 204608
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
Upvotes: 2
Reputation: 185810
What I would do:
for i in {0..200..17}; do ((i % 2)) && echo "$i"; done
17
51
85
119
153
18
((...))
and $((...))
are arithmetic commands, which returns an exit status of 0 if the expression is nonzero, or 1 if the expression is zero. Also used as a synonym for "let", if side effects (assignments) are needed.
See http://mywiki.wooledge.org/ArithmeticExpression
Upvotes: 2