2017-06-02 86 views
0

作爲初學者,我不確定這是否是執行多個循環的最佳方式!雖然它工作得很好,請給我建議,如果有這樣的一種優雅的方式(我不受限的抨擊,但我不熟悉其他語言)Bash:while循環中的兩個循環

#!/bin/bash 
while :; do 
      read -n1 -e -p"Top Levels 1-5: " top_levels 
      if [ "$top_levels" == "1" ]; then 
       echo "top level 1" 
      elif [ "$top_levels" == "2" ]; then 
       while :; do 
          read -n1 -e -p"Sub Levels 1-5: " sub_levels 
          if [ "$sub_levels" == "1" ]; then 
           echo "sub level 1" 
          elif [ "$sub_levels" == "2" ]; then 
           echo "sub level 2" 
          elif [ "$sub_levels" == "3" ]; then 
           while :; do 
              read -n1 -e -p"Final Levels 1-5: " final_levels 
              if [ "$final_levels" == "1" ]; then 
               echo "Final level 1" 
              elif [ "$final_levels" == "2" ]; then 
               echo "Final level 2" 
              elif [ "$final_levels" == "3" ]; then 
               echo "Final level 3" 
              elif [ "$final_levels" == "4" ]; then 
               echo "Final level 4" 
              else 
               echo "bye" 
               break 
              fi 
             done 
          elif [ "$sub_levels" == "4" ]; then 
           echo "sub level 4" 
          else 
           echo "bye" 
           break 
          fi 
         done 
      elif [ "$top_levels" == "3" ]; then 
       echo "top level 3" 
      elif [ "$top_levels" == "4" ]; then 
       echo "top level 4" 
      else 
       echo "bye" 
       exit 
      fi 
     done 
+0

更優雅的做法是什麼?無論答案如何,要求改進工作代碼的問題可能都屬於codereview.stackexchange.com。 – chepner

+1

你的問題真的不清楚。如果一個任務在另一個循環內部需要兩個循環 - 那麼與將兩個循環放入另一個循環內部相比,沒有更好的方法。你應該描述所需的任務:顯示代碼而不解釋你想做什麼是不夠理解的。 – linuxfan

+0

男人,你需要評論。它會幫助人們瞭解你在做什麼,爲什麼。 – SaintHax

回答

0

我會寫這樣

#!/bin/bash 

process_final_levels() { 
    while :; do 
     read -n1 -e -p"### Final Levels 1-5: " final_levels 
     case $final_levels in 
      1) echo "Final level 1";; 
      2) echo "Final level 2";; 
      3) echo "Final level 3";; 
      4) echo "Final level 4";; 
      *) echo "returning to sub levels" 
      break;; 
     esac 
    done 
} 


process_sub_levels() { 
    while :; do 
     read -n1 -e -p"# Sub Levels 1-5: " sub_levels 

     case "$sub_levels" in 
      1) echo "sub level 1" ;; 
      2) echo "sub level 2" ;; 
      3) process_final_levels;; 
      4) echo "sub level 4" ;; 
      *) echo "returning to top levels" 
      break;; 
     esac 
    done 
} 


while :; do 
    # get top levels to work with 
    read -n1 -e -p"Top Levels 1-5: " top_levels 

    case "$top_levels" in 
     1) echo "top level 1" ;; 
     2) process_sub_levels ;; 
     3) echo "top level 3" ;; 
     4) echo "top level 4" ;; 
     *) echo "Bye" 
     exit;; 
    esac 
done 

我改變了提示符並退出字符串,以便更直觀地瞭解您的工作級別。我沒有添加評論,B/C我不知道這是什麼。我功能化了,任何需要修改,測試或維護的代碼都應該功能化。