2

我有一个脚本,我在其中定义了两个数组。现在取决于传递的数组名称(作为参数),我想在下面的函数中处理相同的。早些时候,在我使用之前,我什至没有在变量“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/
4

2 回答 2

2

这是您修改后的有效脚本(在 dreaded 的帮助下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/
于 2012-06-05T14:11:56.230 回答
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/
于 2012-06-06T03:56:53.173 回答