How to iterate over positional parameters in a Bash script?

后端 未结 5 1816
无人共我
无人共我 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:11

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

    0 讨论(0)
  • 2021-01-12 15:12
    args=$@;args=${args// /,}
    grep "foo" $(eval echo file{$args})
    
    0 讨论(0)
  • 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: ${!#}

    0 讨论(0)
  • 2021-01-12 15:20

    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
    
    0 讨论(0)
  • 2021-01-12 15:35

    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
    
    0 讨论(0)
提交回复
热议问题