• Uncategorized

About bash : How-to-iterate-over-positional-parameters-in-a-Bash-script

Question Detail

Where am I going wrong?

I have some files as follows:

filename_tau.txt
filename_xhpl.txt
filename_fft.txt
filename_PMB_MPI.txt
filename_mpi_tile_io.txt

I pass tau, xhpl, fft, mpi_tile_io and PMB_MPI as positional parameters to script as follows:

./script.sh tau xhpl mpi_tile_io fft PMB_MPI

I want grep to search inside a loop, first searching tau, xhpl and so on..

point=$1     #initially points to first parameter
i="0"
while [$i -le 4]
do
  grep "$str" ${filename}${point}.txt
  i=$[$i+1]
  point=$i     #increment count to point to next positional parameter
done

Question Answer

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.

Try something like this:

# Iterating through the provided arguments
for ARG in $*; do
    if [ -f filename_$ARG.txt]; then
        grep "$str" filename_$ARG.txt 
    fi
done

[email protected];args=${args// /,}
grep "foo" $(eval echo file{$args})

You may also like...

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.