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

后端 未结 30 1662
不思量自难忘°
不思量自难忘° 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:06

    I noticed that no one posted an answer showing multi-line echo menu for such simple user input so here is my go at it:

    #!/bin/bash
    
    function ask_user() {    
    
    echo -e "
    #~~~~~~~~~~~~#
    | 1.) Yes    |
    | 2.) No     |
    | 3.) Quit   |
    #~~~~~~~~~~~~#\n"
    
    read -e -p "Select 1: " choice
    
    if [ "$choice" == "1" ]; then
    
        do_something
    
    elif [ "$choice" == "2" ]; then
    
        do_something_else
    
    elif [ "$choice" == "3" ]; then
    
        clear && exit 0
    
    else
    
        echo "Please select 1, 2, or 3." && sleep 3
        clear && ask_user
    
    fi
    }
    
    ask_user
    

    This method was posted in the hopes that someone may find it useful and time-saving.

提交回复
热议问题