2016-08-12 6 views
1

Bash에서 동적 인 parameter expansion이 가능합니까? 동적 매개 변수 확장

$ TEST_1=12345 
$ TEST_2=54321 
$ for i in 1 2; do echo ${TEST_$i}; done 
-bash: ${TEST_$i}: bad substitution 
$ echo ${!TEST_*} 
TEST_1 TEST_2 

원하는 출력 :

If the first character of parameter is an exclamation point (!), it 
introduces a level of variable indirection. Bash uses the value of the 
variable formed from the rest of parameter as the name of the variable; 
this variable is then expanded and that value is used in the rest of 
the substitution, rather than the value of parameter itself. This is 
known as indirect expansion. The exceptions to this are the expansions 
of ${!prefix*} and ${!name[@]} described below. The exclamation point 
must immediately follow the left brace in order to introduce indirec- 
tion. 

즉 :

$ for i in 1 2; do echo ${TEST_$i}; done 
12345 
54321 
+3

필요에 맞게 배열 또는 해시를 사용 하시겠습니까? –

+0

번호가 매겨진 변수를 사용할 때마다 항상 배열을 사용해야합니다. – Barmar

답변

2

당신은 (남성 강타 참조) 간접적 인 매개 변수 확장을 사용할 수 있습니다

for i in 1 2; do var="TEST_$i"; echo "${!var}"; done 

테스트 :

$ TEST_1=12345 
$ TEST_2=54321 
$ for i in 1 2; do var="TEST_$i"; echo "${!var}"; done 
12345 
54321