如何通过索引访问$ * array(或$ @)的元素?
a=( a b c )
set -- a b c
echo ${a[1]}
b # good
echo ${*[1]}
bash: ... bad substitution
echo ${@[1]}
bash: ... bad substitution
答案 0 :(得分:9)
$*
和$@
不是数组,而是在函数或脚本调用时确定的以空格分隔的上下文变量。您可以使用$n
访问其元素,其中n是您想要的参数的位置。
foo() {
echo $1
}
foo one two three # => one
foo "one two" three # => one two
答案 1 :(得分:4)
BUT
你可以分配到另一个阵列并享受乐趣
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'
显然这允许您通过索引${v[7]}
进行访问,因为它只是常规数组
答案 2 :(得分:3)
对于参数,你需要像这样改变它:
while (( "$#" )); do
# $1 contains the next argument
shift
done
答案 3 :(得分:2)
我会在这里重复my answer:
argnum=3 # You want to get the 3rd arg
do-something ${!argnum} # Do something with the 3rd arg
示例:
argc=$#
for (( argn=1; argn<=argc; argn++)); do
if [[ ${!argn} == "foo" ]]; then
echo "Argument $argn of $argc is 'foo'"
fi
done