如何在 shell 脚本中的 ${} 中使用 $1
How to use $1 in ${} in shell script
function print_array(){
NUMBER=1
for i in ${[@]}; do
printf "%d: %s \n" $NUMBER $i
$((NUMBER++))
done
}
我想写一个函数,它可以接受一个数组作为参数并打印数组中的所有内容。
所以我写了类似 ${$1[@]} 的东西,shell 说这是一个“错误的替换”。
有什么方法可以达到同样的效果吗?谢谢!
这段代码有几个问题,但主要的问题是 </code> 永远不会是数组。如果你想将一个数组传递给一个函数,你需要做这样的事情:</p>
<pre><code>print_array(){
NUMBER=1
for i in "${@}"; do
printf "%d: %s \n" $NUMBER "$i"
((NUMBER++))
done
}
myarray=(this is "a test" of arrays)
print_array "${myarray[@]}"
这将输出:
1: this
2: is
3: a test
4: of
5: arrays
请注意,此脚本中的引用很关键:写 ${myarray[@]}
与写 "${myarray[@]}"
不同;有关 $@
与 "$@"
的信息,请参阅 Arrays section of the bash manual for details, as well as the Special Parameters 部分。
function print_array(){
NUMBER=1
for i in ${[@]}; do
printf "%d: %s \n" $NUMBER $i
$((NUMBER++))
done
}
我想写一个函数,它可以接受一个数组作为参数并打印数组中的所有内容。
所以我写了类似 ${$1[@]} 的东西,shell 说这是一个“错误的替换”。
有什么方法可以达到同样的效果吗?谢谢!
这段代码有几个问题,但主要的问题是 </code> 永远不会是数组。如果你想将一个数组传递给一个函数,你需要做这样的事情:</p>
<pre><code>print_array(){
NUMBER=1
for i in "${@}"; do
printf "%d: %s \n" $NUMBER "$i"
((NUMBER++))
done
}
myarray=(this is "a test" of arrays)
print_array "${myarray[@]}"
这将输出:
1: this
2: is
3: a test
4: of
5: arrays
请注意,此脚本中的引用很关键:写 ${myarray[@]}
与写 "${myarray[@]}"
不同;有关 $@
与 "$@"
的信息,请参阅 Arrays section of the bash manual for details, as well as the Special Parameters 部分。