2012-08-13 77 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 

我不知道如何保持在一条线内。