Home > OS >  bash/linux for loop doesnt work like i want it to
bash/linux for loop doesnt work like i want it to

Time:06-12

can someone tell me please why its not work?

the perpose is to find the index of chapterNumber

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

 for chapter_number in "${chapter_number_arr[@]}" ; do
        if [[ $chapter_number == "$chapterNumber" ]] ; then 
            index_file_name=$index2; fi;
    done  

CodePudding user response:

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

for chapter_idx in "${!chapter_number_arr[@]}"; do
  if [[ ${chapter_number_arr[$chapter_idx]} = "$chapterNumber" ]]; then
    index_file_name=$chapter_idx
  fi
done

...will set index_file_name=8. As far as we can tell from the question, this is what you want (it's the index into chapter_number_arr corresponding with chapterNumber).

  • Related