2

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
  • Try ((i=i+$N)) Mar 2, 2016 at 17:24
  • 1
    @Vlad Tarniceru it works like magic! Thanks. Can you also give me a brief explanation why my version doesn't work and yours does? Mar 2, 2016 at 17:27
  • Not a problem :) I think yours should also work, try i+=N, without $. Mar 2, 2016 at 17:29
  • 1
    What you have now should work, but I suspect you want to print the actual parameter? Try ./script.sh 2 p1 p2 p3 p4 p5, your script will print out 2 4 .
    – kos
    Mar 2, 2016 at 17:30
  • 1
    Copied your example. Works alright for me here. Get same output as kos Mar 2, 2016 at 17:35

1 Answer 1

2

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
  • Could you explain, in your answer, why all the extra parentheses are required, and what does the ! do? Mar 3, 2016 at 5:47

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .