Home > OS >  Looping and skipping in bash
Looping and skipping in bash

Time:01-27

when I was solving a Hackerrank Linux shell problem, I stuck.

My task is to use for loops to display only odd natural numbers from 1 to 99.

I tried the followong code but I got wrong. Who can explain this?

My code:

for i in {1..100};
do
  if [[$((i % 2)) !=  0 ]] ;then
    echo "$i"
  fi
done

problem link

only odd numbers from 1 to 99

CodePudding user response:

this line: if [[$((i % 2)) != 0 ]] ;then should have a space after [[: if [[ $((i % 2)) != 0 ]] ;then

CodePudding user response:

I suggest starting at 1 and then increasing by 2 at a time.

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

CodePudding user response:

What you were trying to do -

for i in {1..100}; do ((i%2))&&echo $i; done

Cyrus' is better.

for i in {1..100..2}; eho $i; done

And shellcheck.net would have told you the problem immediately.

Line 3:
  if [[$((i % 2)) !=  0 ]] ;then
     ^-- SC1035 (error): You need a space after the [[ and before the ]].

Bookmark it. Use it regularly.

  •  Tags:  
  • bash
  • Related