Bash script: always show menu after loop execution

前端 未结 3 1013
攒了一身酷
攒了一身酷 2021-01-13 04:55

I\'m using a bash script menu like this:

#!/bin/bash
PS3=\'Please enter your choice: \'
options=(\"Option 1\" \"Option 2\" \"Option3\" \"Quit\")
select opt i         


        
相关标签:
3条回答
  • 2021-01-13 04:58

    You can also do something like:

    #!/bin/bash
    
    PS3='Please enter your choice: '
    options=("Option 1" "Option 2" "Option 3" "Quit")
    select opt in "${options[@]}"
    do
        case $opt in
            "Option 1")
                echo "you chose choice 1"
                ;;
            "Option 2")
                echo "you chose choice 2"
                ;;
            "Option 3")
                echo "you chose choice 3"
                ;;
            "Quit")
                break
                ;;
            *) echo invalid option;;
        esac
        counter=1
        SAVEIFS=$IFS
        IFS=$(echo -en "\n\b")   # we set another delimiter, see also: https://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html
        for i in ${options[@]};
        do
            echo $counter')' $i
            let 'counter+=1'
        done
        IFS=$SAVEIFS
    done
    
    0 讨论(0)
  • 2021-01-13 05:06

    just modified your script like below. its working for me !

     #!/bin/bash
     while true
     do
     PS3='Please enter your choice: '
     options=("Option 1" "Option 2" "Option 3" "Quit")
     select opt in "${options[@]}" 
     do
         case $opt in
             "Option 1")
                 echo "you chose choice 1"
                 break
                 ;;
             "Option 2")
                 echo "you chose choice 2"
                 break
                 ;;
             "Option 3")
                 echo "you chose choice 3"
                 break
                 ;;
             "Quit")
                 echo "Thank You..."                 
                 exit
                 ;;
             *) echo invalid option;;
         esac
     done
     done
    
    0 讨论(0)
  • 2021-01-13 05:21

    Make it beautiful and userfriendly ;-)

    #!/bin/bash
    
    while :
    do
        clear
        cat<<EOF
        ==============================
        Menusystem experiment
        ------------------------------
        Please enter your choice:
    
        Option (1)
        Option (2)
        Option (3)
               (Q)uit
        ------------------------------
    EOF
        read -n1 -s
        case "$REPLY" in
        "1")  echo "you chose choice 1" ;;
        "2")  echo "you chose choice 2" ;;
        "3")  echo "you chose choice 3" ;;
        "Q")  exit                      ;;
        "q")  echo "case sensitive!!"   ;; 
         * )  echo "invalid option"     ;;
        esac
        sleep 1
    done
    

    Replace the echos in this example with function calls or calls to other scripts.

    0 讨论(0)
提交回复
热议问题