Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/shell/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/windows/14.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Bash 连接两个变量,每个变量指向不同的内容_Bash_Shell_Variables - Fatal编程技术网

Bash 连接两个变量,每个变量指向不同的内容

Bash 连接两个变量,每个变量指向不同的内容,bash,shell,variables,Bash,Shell,Variables,我想做一个“for”循环,其中两个变量将被连接。情况是这样的 初始变量集,每个变量指向一个文件: 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 但是我没有成功地

我想做一个“for”循环,其中两个变量将被连接。情况是这样的

初始变量集,每个变量指向一个文件:

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

但是我没有成功地得到初始变量的内容。如何实现这一点?

您可以很容易地获得变量的名称:

for today in ${!weather_*}; do
    echo cat "${!today}"
done
cat /home/me/foo
cat /home/me/bar
cat /home/me/sth
但是如果您使用的是bash4+,那么可以使用关联数组来实现这一点。在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

您可以很容易地获得变量的名称:

for today in ${!weather_*}; do
    echo cat "${!today}"
done
cat /home/me/foo
cat /home/me/bar
cat /home/me/sth
但是如果您使用的是bash4+,那么可以使用关联数组来实现这一点。在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

导入临时变量,然后使用间接展开(由
字符引入)


但是我不知道如何保持在一行之内。

在生成临时变量后使用间接展开(由
字符引入)


但是我不知道如何保持在一行之内。

当有其他选项可用时避免
eval
当有其他选项可用时避免
eval
谢谢,这正是我想要的:)你也可以避免硬编码数组键列表:
在“${!weather[@]}”中为今天编写;do
@chepner谢谢,我全神贯注于避免eval,甚至没有注意到硬编码。修复。谢谢,这正是我想要的:)您也可以避免硬编码数组键列表:
在“${!weather[@]}”中用于今天;do
@chepner谢谢,我全神贯注于避免eval,甚至没有注意到硬编码。固定的。