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 등과 같은 적절한 스크립트 언어로 전환하고 싶을 수도 있다는 강력한 표시입니다.