For Loop with Variable Increment

I have a small shell script and what I want to do when it is run is to display each N'th parameter entered by the user, where N is the first parameter. Ex: for input 2 3 4 5 6 I should display 3 5. What I have until now:

N=$1
for ((i=2;i<$#;i+=$N))
do
    echo -n ${i}" "
done

However, I get a syntax error: operand expected at this part: i+=$N. How can I solve this? If I replace i+=$N with, say, i+=2, it works. But i want N there...

9

1 Answer

So in order to get your code work as you wish, you should do something like:

N=$1
for ((i=2;i<$#;((i=i+$N))))
do
  echo -n ${!i}" "
done

Note the ! before i.

Good luck :)

1

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Chloe Bennett

Chloe Bennett

Culture, Media & Entertainment Columnist

Chloe Bennett explores the intersection of pop culture, streaming entertainment, digital trends, and contemporary lifestyle. Her weekly commentary reaches thousands of culture enthusiasts.

Share this article
Twitter Facebook Pinterest