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

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

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

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

我可以修改循环来检查它是否在第一次迭代中,并改变其行为,但这似乎太骇人听闻了。一定有一个简单的方法可以提取出第一个参数然后循环遍历剩下的参数,但是我找不到它。

98919 次浏览

使用 shift

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

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

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

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

如果出于某种原因,您希望保留参数,因为 shift是破坏性的,那么这可能是有用的。

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