bash 在bash中从$@中删除第一个元素

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2701400/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 19:13:50  来源:igfitidea点击:

Remove first element from $@ in bash

arraysbash

提问by Herms

I'm writing a bash script that needs to loop over the arguments passed into the script. However, the first argument shouldn't be looped over, and instead needs to be checked before the loop.

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

If I didn't have to remove that first element I could just do:

如果我不必删除第一个元素,我可以这样做:

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

I could modify the loop to check if it's in its first iteration and change the behavior, but that seems way too hackish. There's got to be a simple way to extract the first argument out and then loop over the rest, but I wasn't able to find it.

我可以修改循环以检查它是否处于第一次迭代并更改行为,但这似乎太hackish了。必须有一种简单的方法来提取第一个参数,然后遍历其余参数,但我找不到它。

回答by Amber

Use shift?

使用shift?

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

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

Basically, read $1for the first argument before the loop (or $0if what you're wanting to check is the script name), then use shift, then loop over the remaining $@.

基本上,$1在循环之前读取第一个参数(或者$0如果您要检查的是脚本名称),然后使用shift,然后循环剩余的$@.

回答by Paused until further notice.

Another variation uses array slicing:

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

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

This might be useful if, for some reason, you wanted to leave the arguments in place since shiftis destructive.

如果出于某种原因,您希望将参数留在原处,这可能很有用,因为shift它具有破坏性。

回答by nos

firstitem=
shift;
for item in "$@" ; do
  #process item
done

回答by James

q=${@:0:1};[  ] && set ${@:2} || set ""; echo $q

EDIT

编辑

> 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;

> [  ] 
# checks that  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

An Example of pop with regular array

带有常规数组的 pop 示例

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