How to iterate over positional parameters in a Bash script?

后端 未结 5 1817
无人共我
无人共我 2021-01-12 14:39

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         


        
5条回答
  •  礼貌的吻别
    2021-01-12 15:17

    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: ${!#}

提交回复
热议问题