在任何 POSIX shell 中,
set -- "$@" "value"
Run Code Online (Sandbox Code Playgroud)
将添加value
到位置参数列表的末尾(它实际上会用一个新的更长的列表替换列表),并且
set -- "value" "$@"
Run Code Online (Sandbox Code Playgroud)
会在开头添加它(并且在技术上shift
与shift
删除第一个元素的 a 相反)。这适用于zsh
。
将--
用于保护下面的值意外被翻译为选项,万一他们下手-
。
特殊变量$@
几乎是专门使用的,"$@"
因为这会扩展到单独引用的每个位置参数的值。该表达式"$@ somethingelse"
将扩展为单独引用的位置参数列表,<space>somethingelse
并附加到最后一个。
要将位置参数的值用作由空格分隔的单个字符串(或任何$IFS
可能的第一个字符),请使用"$*"
("$* somethingelse"
定义为单个字符串)。然而,在这种情况下,这不是您想要做的,因为它会将您的值列表折叠为一个值。
具体而言zsh
,除了@Kusalananda 显示的标准之外set -- "$@" ...
,位置参数也可以通过$argv
数组获得(如 csh 中),因此您还可以执行以下操作:
argv+=arg # append one argument to the end
argv+=(arg2 arg3) # append several arguments
argv[1,0]=(arg1 arg2) # insert in front
argv[3,0]=(x) # insert before the 3rd element
2+=(x) # same as above (insert after the 2nd)
2+=x # append x to the second argument (not to confuse with
# the above).
argv[2,5]=(y) # replace 4 elements 2 to 5 with one y argument
argv[3,-1]=() # truncate
1=() # same as "shift"
Run Code Online (Sandbox Code Playgroud)