将关联数组作为参数传递给Bash

时间:2013-07-09 20:20:25

标签: linux bash shell

将关联数组作为参数传递给函数以避免重复必须迭代多个关联数组的最佳方法是什么?这样我可以给函数任意打印的数组。这就是我所拥有的:

# Snippet

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

print_weapons() {
  for i in "${!weapons[@]}"; do
    printf "%s\t%d\n" "$i" "${weapons[$i]}"
  done
}

print_weapons

4 个答案:

答案 0 :(得分:10)

您可以使用function DisplayCorrectSections() { var SectionSelection = GetFieldValue("Nationality"); if (SectionSelection == "EEA" ) { EnableRtwDocs(); DisableVisaInformation(); DisableValidVisaPanel(); } if (SectionSelection == "Non EEA") { DisableRtwDocs(); EnableVisaInformation(); EnableValidVisaPanel(); } } 作为参考

local -n

答案 1 :(得分:5)

我认为你不能将关联数组作为参数传递给函数。您可以使用以下hack解决问题:

#!/bin/bash

declare -A weapons=(
  ['Straight Sword']=75
  ['Tainted Dagger']=54
  ['Imperial Sword']=90
  ['Edged Shuriken']=25
)

function print_array {
    eval "declare -A arg_array="${1#*=}
    for i in "${!arg_array[@]}"; do
       printf "%s\t%s\n" "$i ==> ${arg_array[$i]}"
    done
}

print_array "$(declare -p weapons)" 

输出

Imperial Sword ==> 90   
Tainted Dagger ==> 54   
Edged Shuriken ==> 25   
Straight Sword ==> 75   

答案 2 :(得分:1)

使用带有常规数组的variable indirection非常丑陋,使用关联数组很困难 - 我没有找到迭代键的方法。

我想知道你所需要的只是declare -p

print_array() { declare -p $1; }
print_array weapons
declare -A weapons='(["Imperial Sword"]="90" ["Tainted Dagger"]="54" ["Edged Shuriken"]="25" ["Straight Sword"]="75" )'

或者,更漂亮:

print_array() { declare -p $1 | sed 's/[[)]/\n&/g'; }
print_array weapons
declare -A weapons='(
["Imperial Sword"]="90" 
["Tainted Dagger"]="54" 
["Edged Shuriken"]="25" 
["Straight Sword"]="75" 
)'

答案 3 :(得分:-1)

#!/bin/bash

   declare -A dict

   dict=(
    [ke]="va"
    [ys]="lu"
    [ye]="es" 
   ) 

   fun() {
     for i in $@; do
       echo $i
     done
    }

   fun ${dict[@]} 

# ||${dict[key]} || ${!dict[@]} (array keys here jackass) || ${dict[$1]} || ${dict[@]}