怎么样:
eval `./show-devices 192.168.1.2 | grep volume | while read d v ;do
echo $(basename $d)=$v
done`
但是,您将不确定变量的名称。所以最好使用关联数组:
# declare the array
declare -A volumes
# Assign values to the array
eval `./show-devices 192.168.1.2 | grep volume | while read d v ;do
echo volumes[$(basename $d)]=$v
done`
# Use the array
for i in "${!volumes[@]}"; do
echo "Key:$i , Value:${volumes[$i]}"
# Declare all the variables with the values as asked by question
eval $i=${volumes[$i]}
done
说明:| while read d v
循环上一个命令的输出,每行读取 2 个值。basename $d
给我设备的基本名称,$v 包含与设备关联的卷。这被分配到用volumes
声明的关联数组中declare -A volumes
。while
循环在子 shell 中运行并在当前 shell 中打印和评估它,实际分配值volumes[sda]=...
。eval
用法:for
循环是一个用法示例。"${!volumes[@]}"
是volumes
数组的键列表,for
循环遍历它们并打印与volumes
数组中每个键关联的值。
编辑: