bash: choose default from case when enter is pressed in a “select” prompt

后端 未结 4 1400
说谎
说谎 2021-02-05 16:55

I\'m prompting questions in a bash script like this:

optionsAudits=(\"Yep\" \"Nope\")
    echo \"Include audits?\"
    select opt in \"${optionsAudits[@]}\"; do
         


        
4条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-05 17:27

    Your problem is due to the fact that select will ignore empty input. For your case, read will be more suitable, but you will lose the utility select provides for automated menu creation.

    To emulate the behaviour of select, you could do something like that :

    #!/bin/bash
    optionsAudits=("Yep" "Nope")
    while : #infinite loop. be sure to break out of it when a valid choice is made
    do
        i=1
        echo "Include Audits?"
        #we recreate manually the menu here
        for o in  "${optionsAudits[@]}"; do
            echo "$i) $o"
            let i++
        done
    
        read reply
        #the user can either type the option number or copy the option text
        case $reply in
            "1"|"${optionsAudits[0]}") includeAudits=true; break;;
            "2"|"${optionsAudits[1]}") includeAudits=false; break;;
            "") echo "empty"; break;;
            *) echo "Invalid choice. Please choose an existing option number.";;
        esac
    done
    echo "choice : \"$reply\""
    

提交回复
热议问题