How to iterate over positional parameters in a Bash script?

Set up your for loop like this. With this syntax, the loop iterates over the positional parameters, assigning each one to 'point' in turn.

for point; do
  grep "$str" ${filename}${point}.txt 
done

There is more than one way to do this and, while I would use shift, here's another for variety. It uses Bash's indirection feature:

#!/bin/bash
for ((i=1; i<=$#; i++))
do
    grep "$str" ${filename}${!i}.txt
done

One advantage to this method is that you could start and stop your loop anywhere. Assuming you've validated the range, you could do something like:

for ((i=2; i<=$# - 1; i++))

Also, if you want the last param: ${!#}


See here, you need shift to step through positional parameters.

Tags:

Scripting

Bash