我有一个脚本,我已经定义了两个数组。现在,根据传递的数组名称(作为参数),我想在下面的函数中处理相同的内容。早些时候,在使用${!}
现在的问题是,当我打印数组内容(或该数组中的元素数量)时,我只得到第一个元素。
有什么建议吗?
脚本:
#!/bin/bash
APP=$1
process_data() {
ARRAY="${!1}"
echo "No of array elements: ${#ARRAY[@]}"
echo "Array content: ${ARRAY[@]}"
}
ORADATA=(
"oraserver/content:abcDaily/ORAServer/"
"oraserver/w3s-ix86:abcDaily/ORAServer/"
)
SQLDATA=(
"sqlserver/content:abcDaily/SQLServer/"
"sqlserver/w3s-ix86:abcDaily/SQLServer/"
)
process_data ${APP[@]}
命令:
-bash-2.05b$ ./testarray.sh ORADATA
输出:
No of array elements: 1
Array content: oraserver/content:abcDaily/ORAServer/
答案 0 :(得分:2)
以下是您修改过的脚本(在可怕的eval
的帮助下):
#!/bin/bash
APP=$1
process_data() {
ARRAY=( $(eval echo \${$1[@]}) )
echo "No of array elements: ${#ARRAY[@]}"
echo "Array content: ${ARRAY[@]}"
}
ORADATA=(
"oraserver/content:abcDaily/ORAServer/"
"oraserver/w3s-ix86:abcDaily/ORAServer/"
)
SQLDATA=(
"sqlserver/content:abcDaily/SQLServer/"
"sqlserver/w3s-ix86:abcDaily/SQLServer/"
)
process_data ${APP[@]}
<强>输出:强>
No of array elements: 2
Array content: oraserver/content:abcDaily/ORAServer/ oraserver/w3s-ix86:abcDaily/ORAServer/
答案 1 :(得分:1)
这是一个没有eval的版本(所以它正确处理数组值中的shell元字符):
#!/bin/bash
APP=$1
process_data() {
ARRAYVAR="$1[@]" # This just textually appends "[@]" to $1
ARRAY=("${!ARRAYVAR}") # Use indirect expansion to get contents of array, store as new array
echo "No of array elements: ${#ARRAY[@]}"
echo "Array content: ${ARRAY[@]}"
}
ORADATA=(
"oraserver/content:abcDaily/ORAServer/"
"oraserver/w3s-ix86:abcDaily/ORAServer/"
)
SQLDATA=(
"sqlserver/content:abcDaily/SQLServer/"
"sqlserver/w3s-ix86:abcDaily/SQLServer/"
)
process_data $APP # Note that APP is not an array, so the [@] bit was irrelevant
示例:
$ ./testarray.sh ORADATA
No of array elements: 2
Array content: oraserver/content:abcDaily/ORAServer/ oraserver/w3s-ix86:abcDaily/ORAServer/