[英]Bash looping through array of arrays
我正在BASH 3.2中編寫一個腳本我有一系列打印機,其中包含我想要循環的屬性,但我沒有得到任何東西。
以下是我期望它的工作方式:
#!/bin/bash
NMR=("NMR_hp_color_LaserJet_3700" "HP Color LaserJet 3700");
R303=("303_HP_Color_LaserJet_CP5225n" 'HP Color LaserJet CP5520 Series');
Printers=("NMR" "R303")
for i in "${Printers[@]}"
do
for x in "${i}"
do
echo "${x[1]}"
done
done
我發現它更接近,因為它輸出所有的值,但我無法定位打印機的特定屬性:
#!/bin/bash
NMR=("NMR_hp_color_LaserJet_3700" "HP Color LaserJet 3700");
R303=("303_HP_Color_LaserJet_CP5225n" 'HP Color LaserJet CP5520 Series');
Printers=("NMR" "R303")
for i in "${Printers[@]}"
do
arrayz="$i[@]"
for x in "${!arrayz}"
do
echo "$x";
done
done
我如何定位特定屬性?
您可以使用indirect variable expansion
:
for i in "${Printers[@]}"; do
j="$i[@]"
a=("${!j}")
echo "${a[@]}"
done
NMR_hp_color_LaserJet_3700 HP Color LaserJet 3700
303_HP_Color_LaserJet_CP5225n HP Color LaserJet CP5520 Series
更新:要獲取特定索引1的元素,您可以使用:
for i in "${Printers[@]}"; do j="$i[@]"; a=("${!j}"); echo "${a[1]}"; done
HP Color LaserJet 3700
HP Color LaserJet CP5520 Series
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.