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...
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...
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 :)