How do I prompt for Yes/No/Cancel input in a Linux shell script?

后端 未结 30 1659
不思量自难忘°
不思量自难忘° 2020-11-22 04:52

I want to pause input in a shell script, and prompt the user for choices.
The standard Yes, No, or Cancel type question.
How d

相关标签:
30条回答
  • 2020-11-22 05:17

    You can use the default REPLY on a read, convert to lowercase and compare to a set of variables with an expression.
    The script also supports ja/si/oui

    read -rp "Do you want a demo? [y/n/c] "
    
    [[ ${REPLY,,} =~ ^(c|cancel)$ ]] && { echo "Selected Cancel"; exit 1; }
    
    if [[ ${REPLY,,} =~ ^(y|yes|j|ja|s|si|o|oui)$ ]]; then
       echo "Positive"
    fi
    
    0 讨论(0)
  • 2020-11-22 05:18

    One simple way to do this is with xargs -p or gnu parallel --interactive.

    I like the behavior of xargs a little better for this because it executes each command immediately after the prompt like other interactive unix commands, rather than collecting the yesses to run at the end. (You can Ctrl-C after you get through the ones you wanted.)

    e.g.,

    echo *.xml | xargs -p -n 1 -J {} mv {} backup/
    
    0 讨论(0)
  • 2020-11-22 05:19
    yn() {
      if [[ 'y' == `read -s -n 1 -p "[y/n]: " Y; echo $Y` ]];
      then eval $1;
      else eval $2;
      fi }
    yn 'echo yes' 'echo no'
    yn 'echo absent no function works too!'
    
    0 讨论(0)
  • 2020-11-22 05:20

    Here's something I put together:

    #!/bin/sh
    
    promptyn () {
        while true; do
            read -p "$1 " yn
            case $yn in
                [Yy]* ) return 0;;
                [Nn]* ) return 1;;
                * ) echo "Please answer yes or no.";;
            esac
        done
    }
    
    if promptyn "is the sky blue?"; then
        echo "yes"
    else
        echo "no"
    fi
    

    I'm a beginner, so take this with a grain of salt, but it seems to work.

    0 讨论(0)
  • 2020-11-22 05:21

    more generic would be:

    function menu(){
        title="Question time"
        prompt="Select:"
        options=("Yes" "No" "Maybe")
        echo "$title"
        PS3="$prompt"
        select opt in "${options[@]}" "Quit/Cancel"; do
            case "$REPLY" in
                1 ) echo "You picked $opt which is option $REPLY";;
                2 ) echo "You picked $opt which is option $REPLY";;
                3 ) echo "You picked $opt which is option $REPLY";;
                $(( ${#options[@]}+1 )) ) clear; echo "Goodbye!"; exit;;
                *) echo "Invalid option. Try another one.";continue;;
             esac
         done
         return
    }
    
    0 讨论(0)
  • 2020-11-22 05:22

    In my case I needed to read from a downloaded script e.g. curl -Ss https://example.com/installer.sh | sh

    The line read yesno < /dev/tty made it

    echo -n "These files will be uploaded. Is this ok? (y/n) "
    read yesno < /dev/tty
    
    if [ "x$yesno" = "xy" ];then
       
       # Yes
    else
    
       # No
    fi
    
    0 讨论(0)
提交回复
热议问题