You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何修改Bash脚本以完整输出数组变量的所有元素?

修正Bash脚本输出

原脚本

#!/bin/bash

tom[0]="28 years old, computer science bs"
tom[1]="41 years old, physics bs"

ryan[0]="32 years old, technician"

mary[0]="25 years old, math bs"
mary[1]="30 years old, chemistry ba"

robert[0]="34 years old, math bs"

for name in robert mary tom ryan  
do  
    echo "name = ${name}:" 
    for who in "${name[@]}"
    do  
        echo "age,degree = ${!name}"  
    done
done

exit 0

当前输出

name = robert:
age,degree = 34 years old, math bs
name = mary:
age,degree = 25 years old, math bs
name = tom:
age,degree = 28 years old, computer science bs
name = ryan:
age,degree = 32 years old, technician

期望输出

name = robert:
age,degree = 34 years old, math bs

name = mary:
age,degree = 25 years old, math bs
age,degree = 30 years old, chemistry ba

name = tom:
age,degree = 28 years old, computer science bs
age,degree = 41 years old, physics bs

name = ryan:
age,degree = 32 years old, technician

问题分析与修正脚本

原脚本存在两个核心问题:一是无法正确遍历以变量名命名的数组元素,二是缺少用户块之间的空行分隔。修正后的脚本如下:

#!/bin/bash

tom[0]="28 years old, computer science bs"
tom[1]="41 years old, physics bs"

ryan[0]="32 years old, technician"

mary[0]="25 years old, math bs"
mary[1]="30 years old, chemistry ba"

robert[0]="34 years old, math bs"

# 控制空行输出,避免开头出现空行
first_user=1
for name in robert mary tom ryan  
do  
    if [ $first_user -ne 1 ]; then
        echo
    fi
    first_user=0
    
    echo "name = ${name}:" 
    # 通过间接引用获取目标数组的所有元素
    eval "target_array=(\${${name}[@]})"
    # 遍历数组每个元素并输出
    for item in "${target_array[@]}"
    do  
        echo "age,degree = ${item}"  
    done
done

exit 0

关键说明

  • 使用eval "target_array=(\${${name}[@]})"实现间接引用,将目标数组的所有元素赋值给临时数组target_array,解决了动态数组名的遍历问题
  • 新增first_user变量控制空行,确保不同用户的输出块之间有且仅有一个空行,同时避免开头出现多余空行
  • 内层循环直接输出临时数组的每个元素,保证数组中所有条目都能被打印

内容的提问来源于stack exchange,提问作者novi2023

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.20 14:42:43