2012-08-13 80 views
1

我想做一個'for'循環,其中兩個變量將被連接。這裏的情況是加入2個變量,每個變量指向不同

初始設置的變量,每一個指向文件:

weather_sunny=/home/me/foo 
weather_rainy/home/me/bar 
weather_cloudy=/home/me/sth 

第二組變量:

sunny 
rainy 
cloudy 

現在,我想要做這樣的事情..

for today in sunny rainy cloudy ; do 
    cat ${weather_$today} 
done 

但是我沒有成功獲取初始變量的內容。我怎樣才能做到這一點?

回答

4

你可以得到的變量容易夠的名字:

for today in ${!weather_*}; do 
    echo cat "${!today}" 
done 
cat /home/me/foo 
cat /home/me/bar 
cat /home/me/sth 

但是如果你使用bash 4+,您可以使用關聯數組這一點。在bash 4,

$ declare -A weather 
$ weather['sunny']=/home/me/sth 
$ weather['humid']=/home/me/oth 
$ for today in "${!weather[@]}"; do echo "${weather[$today]}"; done 
/home/me/sth 
/home/me/oth 
+0

謝謝,正是我一直在尋找:) – user1579465 2012-08-13 13:08:11

+0

你也可以避免硬編碼數組鍵的列表:'今天在'$ {!weather [@]}「;做' – chepner 2012-08-13 14:05:52

+0

@chepner謝謝,我都在避免eval,甚至沒有注意到硬編碼。固定。 – kojiro 2012-08-13 14:22:49

2
for today in sunny rainy cloudy ; do 
    eval e="\$weather_$today" 
    cat $e 
done 
+0

當有其他選項可用時,避免使用'eval'。 – chepner 2012-08-13 13:04:26

1

Inroduce臨時變量,然後使用間接膨脹(通過!字符引入)。

for today in sunny rainy cloudy ; do 
    tmp="weather_$today" 
    cat ${!tmp} 
done 

我不知道如何保持在一條線內。