Discussion:
ShellScript中的動態變數怎麼產生?
(时间太久无法回复)
沙原隱泉
2005-07-05 04:11:46 UTC
Permalink
Shell Script內容如下:

1. #!/bin/ksh
2. LTN_P_IP=192.168.12.8
3. LTN_S_IP=192.168.14.8
4. for linux in LTN{
5. echo "$"$linux"_P_IP" # -->得到結果$LTN_P_IP
6. }

如同第五行,我期望出來的結果應該是192.168.12.8,但出來的結果是$LTN_P_IP?
換句話說,我期望$LTN_P_IP這個變數名稱是動態產生的,但是出來的結果還能繼續
用"$"做變數取值,但是我不知道怎麼做到?可否提供個意見?
--
※ Origin: SayYA 資訊站 <bbs.sayya.org> 
◆ From: nk218-187-12-68.dialup.dynamic.apol.com.tw
沙原隱泉
2005-07-05 04:41:11 UTC
Permalink
※ 引述《sanger (沙原隱泉)》之銘言:
Post by 沙原隱泉
1. #!/bin/ksh
2. LTN_P_IP=192.168.12.8
3. LTN_S_IP=192.168.14.8
4. for linux in LTN{
5. echo "$"$linux"_P_IP" # -->得到結果$LTN_P_IP
6. }
如同第五行,我期望出來的結果應該是192.168.12.8,但出來的結果是$LTN_P_IP?
換句話說,我期望$LTN_P_IP這個變數名稱是動態產生的,但是出來的結果還能繼續
用"$"做變數取值,但是我不知道怎麼做到?可否提供個意見?
哈哈,自己問自己答

eval echo \${$linux"_P_IP"}
這樣就解了

eval is a built-in command,下面是它的解釋
eval [arg ...]
The args are read and concatenated together into a single com-
mand. This command is then read and executed by the shell, and
its exit status is returned as the value of eval. If there are
no args, or only null arguments, eval returns 0.
--
※ Origin: SayYA 資訊站 <bbs.sayya.org> 
◆ From: nk218-187-12-68.dialup.dynamic.apol.com.tw
Loading...