Bash将数组传递给函数会插入空元素

时间:2015-03-12 15:01:16

标签: arrays bash function

我将一个空数组传递给一个函数,在函数中,数组有一个元素,但该元素为空。

#!/bin/bash
#ytest
#==============================================================
function ShowArray
{
echo "in ShowArray"

AlocalArray=("${!1}")

#alternatively you could do it like that
#echo "${AlocalArray[@]}"                      #DEBUG

echo "Showing content of array"

local iMax

   iMax=${#AlocalArray[*]}

   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++))
   do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}


declare -a AARRAY
echo "${AARRAY[@]}"                      #DEBUG
iMax=${#AARRAY[*]}

echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"
ShowArray "$AARRAY"

从剧本的主体我得到:

HERE ARRAYCOUNT: 0 ITEMS in ARRAY

从我得到的功能中:

in ShowArray
Showing content of array
ARRAYCOUNT: 1
ITEM: 

我的代码出了什么问题?提前谢谢。

免责声明:此演示脚本没有任何用处,仅用于演示不当行为。

1 个答案:

答案 0 :(得分:2)

这不是在BASH中传递数组的正确方法,而ShowArray函数没有访问在外部创建的相同数组。

以下是如何在BASH(旧版本和新版本)中传递数组

# works for older BASH version 3 also
ShowArray() {
   echo "in ShowArray -----------------------"
   AlocalArray=("${!1}")
   declare -p AlocalArray
   echo "Showing content of array"

   local iMax=${#AlocalArray[@]}    
   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++)); do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}

# works on BASH versions >4
ShowArray1() {
   echo "in ShowArray1 -----------------------"
   declare -n AlocalArray="$1"
   declare -p AlocalArray
   echo "Showing content of array"

   local iMax=${#AlocalArray[@]}    
   echo "ARRAYCOUNT: $iMax"
   for ((iItem=0; iItem < iMax ; iItem++)); do
      echo "ITEM: ${AlocalArray[$iItem]}"
   done
}

declare -a AARRAY=(foo bar)
declare -p AARRAY
iMax=${#AARRAY[@]}
echo "HERE ARRAYCOUNT: $iMax ITEMS in ARRAY"
ShowArray "AARRAY[@]"
ShowArray1 "AARRAY"

<强>输出:

declare -a AARRAY='([0]="foo" [1]="bar")'
HERE ARRAYCOUNT: 2 ITEMS in ARRAY
in ShowArray -----------------------
declare -a AlocalArray='([0]="foo" [1]="bar")'
Showing content of array
ARRAYCOUNT: 2
ITEM: foo
ITEM: bar
in ShowArray1 -----------------------
declare -n AlocalArray="AARRAY"
Showing content of array
ARRAYCOUNT: 2
ITEM: foo
ITEM: bar