How to iterate over positional parameters in a bash script?

Where am I going wrong?

I have several files:

filename_tau.txt filename_xhpl.txt fiename_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 the script as follows:

 ./script.sh tau xhpl mpi_tile_io fft PMB_MPI 

I want grep to search inside the loop, first search for tau, xhpl, etc.

 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 
+6
scripting bash
source share
5 answers

Set up the for loop as follows. Using this syntax, the cycle is repeated in positional parameters, assigning each of them a β€œpoint” in turn.

 for point; do grep "$str" ${filename}${point}.txt done 
+6
source share

There are several ways to do this, and although I would use shift , here is another for a change. It uses the bash function:

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

One of the advantages of this method is that you can start and stop your loop anywhere. Assuming you checked the range, you could do something like:

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

Also, if you want to get the last parameter: ${!#}

+3
source share

See here , you need to go to the step through the positional parameters.

+2
source share

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 
+1
source share
 args=$@ ;args=${args// /,} grep "foo" $(eval echo file{$args}) 
0
source share

All Articles