Bash/Linux for循环无法按预期查找数组元素索引的问题
脚本无法正常运行的核心原因
- 现有遍历逻辑仅迭代数组的元素值,全程没有定义、更新索引计数变量,代码中引用的
$index2属于未初始化的空值,即使匹配到目标元素,最终赋值给index_file_name的也只是空内容。 - 匹配到目标元素后没有主动终止循环,若数组后续存在与目标值重复的元素,已得到的结果会被错误覆盖。
可直接运行的修复代码
兼容所有Bash版本的写法(手动维护计数器)
数组默认下标从0开始计数,如果需要从1开始算序号,把赋值行的$i改成$((i+1))即可。
chapter_number_arr=(ch-01 ch-02 ch-03 ch-04 ch-05 ch-06 ch-07 ch-08 ch-09 ch-10) chapterNumber=ch-09 index_file_name=-1 # 初始化默认值,-1代表未找到匹配项 for ((i=0; i<${#chapter_number_arr[@]}; i++)); do if [[ ${chapter_number_arr[i]} == "$chapterNumber" ]]; then index_file_name=$i break # 找到匹配项立刻退出循环,避免无效遍历和结果覆盖 fi done # 输出验证结果,ch-09对应的索引为8 echo "目标元素对应索引:$index_file_name"
Bash 4.0+ 更简洁的原生索引遍历写法
Bash原生支持直接遍历数组的所有下标,不需要手动维护计数器:
chapter_number_arr=(ch-01 ch-02 ch-03 ch-04 ch-05 ch-06 ch-07 ch-08 ch-09 ch-10) chapterNumber=ch-09 index_file_name=-1 for index in "${!chapter_number_arr[@]}"; do if [[ ${chapter_number_arr[index]} == "$chapterNumber" ]]; then index_file_name=$index break fi done echo "目标元素对应索引:$index_file_name"
内容的提问来源于stack exchange,提问作者Saar Weinberg
相关产品推荐
相关产品推荐

