# Create a 0-index-based copy of the array of input arguments.
# (You could, however, work with the 1-based pseudo array $@ directly.)
array=( "${@}" )
# Print a concatenation of all input arguments starting with the 9th
# (starting at 0-based index 8), which are passed *individually* to
# `printf`, due to use of `@` to reference the array [slice]
# `%s` as the `printf` format then joins the elements with no separator
# (and no trailing \n).
printf '%s' "${array[@]:8}"
# Alternative: Print the elements separated with a space:
# Note that using `*` instead of `@` causes the array [slice] to be expanded
# to a *single* string using the first char. in `$IFS` as the separator,
# which is a space by default; here you could add a trailing \n by using
# '%s\n' as the `printf` format string.
printf '%s' "${array[*]:8}"
注意array="${@}"不创建一个数组 - 它只是创建一个字符串标量,包括输入数组元素的串联(总是),每个元素由 空格 分隔;要创建一个数组,您必须将它包含在(...) 中。
要根据您在follow-up question 中的要求,从第 9 个用双引号括起来 开始的参数创建一个以空格分隔的单个字符串,请使用以下命令:
printf -v var10 '"%s"' "${array[*]:8}"
您的问题$var10 的最后一个示例调用将包含文字"A B C",包括双引号。
至于将参数 1 到 8 分配给单个变量。:
Jonathan Leffler's helpful answer 展示了如何将前 8 个参数保存在单个变量中。
这是一个算法替代方案,它根据给定的名称前缀和序列号创建单个变量:
n=8 # how many arguments to assign to individual variables
# Create n 'var<i>' variables capturing the first n arguments.
i=0 # variable sequence number
for val in "${array[@]:0:n}"; do
declare "var$((++i))=$val" # create $var<i>, starting with index 1
done
# Print the variables created and their values, using variable indirection.
printf "\nvar<i> variables:\n"
for varName in "${!var@}"; do
printf '%s\n' "$varName=${!varName}"
done