如何在Bash中为每行分配索引并选择首字段作为后续命令变量
解决Bash脚本select菜单展示与选择异常问题
原脚本
#!/usr/bin/env bash job=`cat example.txt` lines=`cat example.txt | cut -d " " -f1` for i in ${!lines[@]}; do echo "$i " ${job[$i]}; done PS3="Select desired job-id to check current status: ENTER HERE!!! => " select id in "${lines[@]}"; do echo "you have selected ${id}" ; echo "looking into ${id}" ; break done
示例文件example.txt内容
53763958 4.01005 my_job me_userid r 2023-01-13T07:39:10.821 1 53763959 0.00000 your_job you_userid hqw 2023-01-13T07:37:29.525 1 53763961 0.00000 his_job he_userid hqw 2023-01-13T07:37:29.923 1 53763929 0.00000 her_job her_userid qw 2023-01-13T07:28:56.918 1
当前错误执行结果
1) 53763958 53763959 53763961 53763929 Select desired job-id to check current status: ENTER HERE!!! => 1 you have selected 53763958 53763959 53763961 53763929 looking into 53763958 53763959 53763961 53763929
期望执行结果
1) 53763958 4.01005 my_job me_userid r 2023-01-13T07:39:10.821 1 2) 53763959 0.00000 your_job you_userid hqw 2023-01-13T07:37:29.525 1 3) 53763961 0.00000 his_job he_userid hqw 2023-01-13T07:37:29.923 1 4) 53763929 0.00000 her_job her_userid qw 2023-01-13T07:28:56.918 1 you have selected: 53763958-my_job
问题根源
原脚本核心问题是未正确将文件内容按行存入数组:
job=$(cat example.txt)将整个文件读为单个字符串,而非数组lines=$(cat example.txt | cut -d " " -f1)将所有job-id拼成单个字符串,而非数组- 后续遍历与select操作时,Bash按空格拆分字符串,导致内容混乱
修正后的脚本
#!/usr/bin/env bash # 按行读取文件内容到数组 readarray -t job_lines < example.txt # 提取所有job-id到单独数组 job_ids=() for line in "${job_lines[@]}"; do job_ids+=("$(echo "$line" | awk '{print $1}')") done PS3="Select desired job-id to check current status: ENTER HERE!!! => " # 用数组索引作为select选项,自动关联完整行内容 select idx in "${!job_lines[@]}"; do # 校验输入有效性 if [[ -z "${job_lines[$idx]}" ]]; then echo "无效选择,请重新输入" continue fi # 提取选中行的关键信息 selected_id="${job_ids[$idx]}" selected_job="$(echo "${job_lines[$idx]}" | awk '{print $3}')" echo -e "\nyou have selected: ${selected_id}-${selected_job}" echo "looking into ${selected_id}" break done
关键说明
- 使用
readarray -t按行读取文件,确保每行是数组独立元素 - 遍历数组提取每行首字段(job-id),后续可直接调用
- 以数组索引作为select选项,让菜单自动按编号展示完整行内容
- 选中后可快速获取job-id等字段,直接传递给后续命令
内容的提问来源于stack exchange,提问作者Nayak
相关产品推荐
相关产品推荐

