以下是示例代码
top_dir=(network_dir telecomm_dir)
network_dir=(dijkstra patricia)
telecomm_dir=(CRC32 FFT adpcm gsm)
for bench in ${top_dir[@]}; do
for subdir in ${$bench[@]}; do
make -C $subdir
done
done
我所拥有的是两个目录,每个目录都有子目录。我想迭代每个目录并执行make
。当我运行此脚本时,它会给我错误消息,
./run.sh: line 21: ${$bench[@]}: bad substitution
是否可以让bash使用变量''bench'来访问network_dir和telecomm_dir?谢谢!
答案 0 :(得分:1)
一个选项是使用解除引用
top_dir=(network_dir telecomm_dir)
network_dir=(dijkstra patricia)
telecomm_dir=(CRC32 FFT adpcm gsm)
for bench in "${top_dir[@]}"; do
arr="${!bench}"
for subdir in "${arr[@]}"; do
make -C "$subdir"
done
done
也使用更多引号
另一种选择是使用关联数组:
declare -A dirs=(
[network_dir]="dijkstra patricia"
[telecomm_dir]="CRC32 FFT adpcm gsm"
)
for bench in "${!dirs[@]}"; do
for subdir in ${dirs[$bench]}; do # requires subdirs with no spaces
make -C "$subdir"
done
done