2010-04-08 142 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