开发者

How to iterate over positional parameters in a Bash script?

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_til开发者_JAVA技巧e_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


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


args=$@;args=${args// /,}
grep "foo" $(eval echo file{$args})
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜