代码之家  ›  专栏  ›  技术社区  ›  Herms

从bash中的$@中删除第一个元素[duplicate]

  •  98
  • Herms  · 技术社区  · 16 年前

    我正在编写一个bash脚本,它需要循环传递到脚本中的参数。但是,第一个参数不应该循环,而是需要在循环之前进行检查。

    如果我不需要移除第一个元素,我可以:

    for item in "$@" ; do
      #process item
    done
    

    我可以修改循环以检查它是否在其第一次迭代中并更改行为,但这看起来太老套了。必须有一个简单的方法来提取出第一个参数,然后遍历其余的参数,但是我找不到它。

    4 回复  |  直到 9 年前
        1
  •  119
  •   Amber    16 年前

    使用 shift ?

    http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html

    基本上,读 $1 循环之前的第一个参数(或 $0 如果要检查的是脚本名,则使用 转移 ,然后循环剩余的 $@ .

        2
  •  118
  •   Dennis Williamson    16 年前

    另一个变体使用数组切片:

    for item in "${@:2}"
    do
        process "$item"
    done
    

    如果出于某种原因,您希望保留争论的位置 shift 是破坏性的。

        3
  •  35
  •   twasbrillig    9 年前
    firstitem=$1
    shift;
    for item in "$@" ; do
      #process item
    done
    
        4
  •  5
  •   Tegra Detra    12 年前
    q=${@:0:1};[ ${2} ] && set ${@:2} || set ""; echo $q
    

    编辑

    > q=${@:1}
    # gives the first element of the special parameter array ${@}; but ${@} is unusual in that it contains (? file name or something ) and you must use an offset of 1;
    
    > [ ${2} ] 
    # checks that ${2} exists ; again ${@} offset by 1
        > && 
        # are elements left in        ${@}
          > set ${@:2}
          # sets parameter value to   ${@} offset by 1
        > ||
        #or are not elements left in  ${@}
          > set ""; 
          # sets parameter value to nothing
    
    > echo $q
    # contains the popped element
    

    具有正则数组的pop示例

       LIST=( one two three )
        ELEMENT=( ${LIST[@]:0:1} );LIST=( "${LIST[@]:1}" ) 
        echo $ELEMENT