无法检索所有数组元素

时间:2012-06-05 12:49:38

标签: arrays bash

我有一个脚本,我已经定义了两个数组。现在,根据传递的数组名称(作为参数),我想在下面的函数中处理相同的内容。早些时候,在使用${!}

之前,我甚至没有在变量'ARRAY'中获得任何元素

现在的问题是,当我打印数组内容(或该数组中的元素数量)时,我只得到第一个元素。

有什么建议吗?

脚本:

#!/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/

2 个答案:

答案 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/