2010-04-08 100 views
2

我有一個腳本,它有一個Select語句去多個子選擇語句,但是一旦我似乎無法弄清楚如何讓它回到主腳本。還可能的話我想它重新列出你使用一個循環做到這一點的選項Bash Shell腳本:嵌套Select語句

#!/bin/bash 
      PS3='Option = ' 
      MAINOPTIONS="Apache Postfix Dovecot All Quit" 
      APACHEOPTIONS="Restart Start Stop Status" 
      POSTFIXOPTIONS="Restart Start Stop Status" 
      DOVECOTOPTIONS="Restart Start Stop Status" 
      select opt in $MAINOPTIONS; do 
       if [ "$opt" = "Quit" ]; then 
       echo Now Exiting 
       exit 
       elif [ "$opt" = "Apache" ]; then 
       select opt in $APACHEOPTIONS; do 
       if [ "$opt" = "Restart" ]; then 
       sudo /etc/init.d/apache2 restart 
       elif [ "$opt" = "Start" ]; then 
       sudo /etc/init.d/apache2 start 
       elif [ "$opt" = "Stop" ]; then 
       sudo /etc/init.d/apache2 stop 
       elif [ "$opt" = "Status" ]; then 
       sudo /etc/init.d/apache2 status 
       fi 
       done 
       elif [ "$opt" = "Postfix" ]; then 
       select opt in $POSTFIXOPTIONS; do 
       if [ "$opt" = "Restart" ]; then 
       sudo /etc/init.d/postfix restart 
       elif [ "$opt" = "Start" ]; then 
       sudo /etc/init.d/postfix start 
       elif [ "$opt" = "Stop" ]; then 
       sudo /etc/init.d/postfix stop 
       elif [ "$opt" = "Status" ]; then 
       sudo /etc/init.d/postfix status 
       fi 
       done 
       elif [ "$opt" = "Dovecot" ]; then 
       select opt in $DOVECOTOPTIONS; do 
       if [ "$opt" = "Restart" ]; then 
       sudo /etc/init.d/dovecot restart 
       elif [ "$opt" = "Start" ]; then 
       sudo /etc/init.d/dovecot start 
       elif [ "$opt" = "Stop" ]; then 
       sudo /etc/init.d/dovecot stop 
       elif [ "$opt" = "Status" ]; then 
       sudo /etc/init.d/dovecot status 
       fi 
       done 
       elif [ "$opt" = "All" ]; then 
       sudo /etc/init.d/apache2 restart 
       sudo /etc/init.d/postfix restart 
       sudo /etc/init.d/dovecot restart 
       fi 
       done 

回答

2

的是Bourne shell有一個有用的構造,有時我真希望C的。

你可以用「破發N」,其中n可以是2,3,等突破嵌套控制結構的

所以,從你的嵌套子選擇,你可以發出break 2;找回到頂層。儘管如此,我並不完全肯定你想達到的目標。

3

..

while true 
do 
... 
... 
    read -p "do you want to continue (Q)uit?" choice 
    case "$choice" in 
    Q|q) break;; #or exit your script 
    esac 
... 
done 
6

則通常將巢穴caseselect語句,把整個事情的循環語句:

while true 
do 
    select option in $options 
    do 
     case $option in 
      choice1) 
       do_something 
       ;; 
      choice2) 
       select sub_option in $sub_options 
       do 
        case $sub_option in 
         sub_choice1) 
          another_thing 
          ;; 
         sub_choice2) 
          break # return to current (sub) menu 
          ;; 
         sub_choice3) 
          break 2 # return to parent menu 
          ;; 
        esac 
      choice3) 
       break # return to current (main) menu 
       ;; 
      choice4) 
       break 2 # exit the while loop so cleanup can be done at the end of the script 
     esac 
    done 
done 
do_cleanup