访问关联数组的值,其名称作为 bash 函数内的参数传递

访问关联数组的值,其名称作为 bash 函数内的参数传递

我在 bash 脚本中有一些关联数组,我需要将它们传递给一个函数,在该函数中我还需要访问键和值。

declare -A gkp=( \
   ["arm64"]="ARM-64-bit" \
   ["x86"]="Intel-32-bit" \
)

fv()
{
   local entry="$1"
   echo "keys: ${!gkp[@]}"
   echo "vals: ${gkp[@]}"
   local arr="$2[@]"
   echo -e "\narr entries: ${!arr}"
}

fv $1 gkp

上述输出:

kpi: arm64 x86
kpv: ARM-64-bit Intel-32-bit

arr entries: ARM-64-bit Intel-32-bit

我可以获取传递给函数的数组值,但无法弄清楚如何在函数中打印键(即“arm64”“x86”)。

请帮忙。

答案1

您需要将arr变量设置为 nameref。从man bash

   A  variable  can be assigned the nameref attribute using the -n option
   to the declare or local builtin commands (see the descriptions of  de‐
   clare  and local below) to create a nameref, or a reference to another
   variable.  This allows variables to be manipulated indirectly.   When‐
   ever  the  nameref  variable is referenced, assigned to, unset, or has
   its attributes modified (other than using or changing the nameref  at‐
   tribute  itself),  the operation is actually performed on the variable
   specified by the nameref variable's value.  A nameref is commonly used
   within shell functions to refer to a variable whose name is passed  as
   an  argument  to  the  function.   For instance, if a variable name is
   passed to a shell function as its first argument, running
          declare -n ref=$1
   inside the function creates a nameref variable ref whose value is  the
   variable  name  passed  as the first argument.  References and assign‐
   ments to ref, and changes to its attributes,  are  treated  as  refer‐
   ences,  assignments, and attribute modifications to the variable whose
   name was passed as $1.  If the control variable in a for loop has  the
   nameref attribute, the list of words can be a list of shell variables,
   and a name reference will be established for each word in the list, in
   turn,  when the loop is executed.  Array variables cannot be given the
   nameref attribute.  However, nameref  variables  can  reference  array
   variables  and subscripted array variables.  Namerefs can be unset us‐
   ing the -n option to the unset builtin.  Otherwise, if unset  is  exe‐
   cuted with the name of a nameref variable as an argument, the variable
   referenced by the nameref variable will be unset.

实际上,这看起来像:

#!/bin/bash

declare -A gkp=(
   ["arm64"]="ARM-64-bit" 
   ["x86"]="Intel-32-bit" 
)

fv()
{
   local entry="$1"
   echo "keys: ${!gkp[@]}"
   echo "vals: ${gkp[@]}"
   local -n arr_name="$2"
   
   echo -e "\narr entries: ${!arr_name[@]}"
}

fv "$1" gkp

运行它会给出:

$ foo.sh foo
keys: x86 arm64
vals: Intel-32-bit ARM-64-bit

arr entries: x86 arm64

强制性警告:如果您发现自己需要在 shell 脚本中执行类似的操作,通常强烈表明您可能想要切换到适当的脚本语言,例如 Perl 或 Python 或其他任何语言。

相关内容