代码之家  ›  专栏  ›  技术社区  ›  Sharat Chandra

如何在Bash脚本中迭代位置参数?

  •  6
  • Sharat Chandra  · 技术社区  · 16 年前

    我有一些文件如下:

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

    我通过 tau , xhpl , fft , mpi_tile_io PMB_MPI 作为脚本的位置参数,如下所示:

    ./script.sh tau xhpl mpi_tile_io fft PMB_MPI
    

    我希望grep在循环中搜索,首先搜索tau、xhpl等等。。

    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
    
    5 回复  |  直到 5 年前
        1
  •  9
  •   Steve K    16 年前

    for point; do
      grep "$str" ${filename}${point}.txt 
    done
    
        2
  •  5
  •   Dennis Williamson    16 年前

    shift ,这是另一种多样性。它使用Bash的间接功能:

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

    这种方法的一个优点是可以在任何地方启动和停止循环。假设您已经验证了范围,您可以执行以下操作:

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

    ${!#}

        3
  •  2
  •   Alberto Zaccagni    16 年前

    here ,则需要shift单步执行位置参数。

        4
  •  1
  •   Bobby    16 年前

    试着这样做:

    # Iterating through the provided arguments
    for ARG in $*; do
        if [ -f filename_$ARG.txt]; then
            grep "$str" filename_$ARG.txt 
        fi
    done
    
        5
  •  0
  •   ghostdog74    16 年前
    args=$@;args=${args// /,}
    grep "foo" $(eval echo file{$args})