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

必須の警告:シェルスクリプトでこれを行う必要がある場合は、通常、PerlやPythonなどの適切なスクリプト言語に切り替えたい場合があるという強力なマークです。

おすすめ記事