Remove first element from $@ in bash
本问题已经有最佳答案,请猛点这里访问。
我正在编写一个bash脚本,需要循环传递给脚本的参数。 但是,第一个参数不应该循环,而是需要在循环之前进行检查。
如果我不必删除第一个元素,我可以这样做:
1 2 3 | for item in"$@" ; do #process item done |
我可以修改循环以检查它是否在第一次迭代中并改变行为,但这似乎太过于苛刻。 必须有一个简单的方法来提取第一个参数然后循环其余的,但我无法找到它。
使用
http://tldp.org/LDP/Bash-Beginners-Guide/html/sect_09_07.html
基本上,在循环之前读取
另一种变体使用数组切片:
1 2 3 4 | for item in"${@:2}" do process"$item" done |
如果出于某种原因,您希望保留参数,因为
1 2 3 4 5 | firstitem=$1 shift; for item in"$@" ; do #process item done |
1 | q=${@:0:1};[ ${2} ] && set ${@:2} || set""; echo $q |
编辑
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | > 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 |
弹出常规数组的示例
1 2 3 | LIST=( one two three ) ELEMENT=( ${LIST[@]:0:1} );LIST=("${LIST[@]:1}" ) echo $ELEMENT |