![Bash에서 간접 배열의 크기를 얻는 방법은 무엇입니까?](https://linux55.com/image/7437/Bash%EC%97%90%EC%84%9C%20%EA%B0%84%EC%A0%91%20%EB%B0%B0%EC%97%B4%EC%9D%98%20%ED%81%AC%EA%B8%B0%EB%A5%BC%20%EC%96%BB%EB%8A%94%20%EB%B0%A9%EB%B2%95%EC%9D%80%20%EB%AC%B4%EC%97%87%EC%9E%85%EB%8B%88%EA%B9%8C%3F.png)
평가를 사용하지 마십시오.
이것은 작동하지 않습니다:
astr=(a b c)
str="#astr[@]"
echo "${!str}"
답변1
팁에서여기, 나는 이것을 할 수 있었습니다:
astr=(a b c)
declare -n astrRef="astr"
echo ${#astrRef[@]}
또한 이러한 배열을 생성하거나 단순히 간접 할당을 통해 생성할 수도 있습니다.
declare -n astrRef="astr"
astrRef=(d e f)
declare -p astrRef astr
astrRef+=(g)
declare -p astrRef astr
답변2
이것은 어떻습니까? 적어도 효과가 있습니다.배쉬 3.x위에:
astr=(a b c)
str=astr[@] # Our reference to an array
local arr=("${!str}") # Copy into an array using indirect ref
echo ${#arr[*]}
# 3
bstr=("a foo" "a bar" "a fox" "a buzz")
str=bstr[@]
local arr=("${!str}")
echo ${#arr[*]}
# 4
함수에 로컬로 local
작업 변수를 유지하기 위해 키워드를 사용 하지만 이는 선택 사항입니다. arr
실제로 bash 제한으로 인해 arr
배열의 요소에 (간접적으로) 액세스하는 데 사용할 수도 있습니다. 예를 들면 다음과 같습니다.
echo ${arr[1]} # Print 2nd element
echo ${#arr[1]} # ... print its size
(테스트됨배쉬 3.1.23, 배쉬 4.3.48 및 4.4.12)