按索引访问$*(或$ @)的元素

And*_*rei 8 bash

如何通过索引访问$*array(或$ @)的eleent?
例如,让我们采用3元素数组和index = 1:

a=( a b c )
set -- a b c
echo ${a[1]}
b               # good
echo ${*[1]}
bash: ... bad substitution

echo ${@[1]}
bash: ... bad substitution
Run Code Online (Sandbox Code Playgroud)

小智 9

$*并且$@不是数组,而是在函数或脚本调用时确定的空格分隔的上下文变量.您可以使用其中的元素访问$n,其中n是您想要的参数的位置.

foo() {
  echo $1
}

foo one two three # => one
foo "one two" three # => one two
Run Code Online (Sandbox Code Playgroud)


seh*_*ehe 5

您可以分配给另一个数组并玩得开心

function test
{
    declare -a v=("$@")
    for a in "${v[@]}"; do echo "'$a'"; done
}

$ test aap noot mies
'aap'
'noot'
'mies'

$ test aap noot mies\ broer
'aap'
'noot'
'mies broer'
Run Code Online (Sandbox Code Playgroud)

显然这允许您通过索引访问,${v[7]}因为它只是一个常规数组