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

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

    I've used the case statement a couple of times in such a scenario, using the case statment is a good way to go about it. A while loop, that ecapsulates the case block, that utilizes a boolean condition can be implemented in order to hold even more control of the program, and fulfill many other requirements. After the all the conditions have been met, a break can be used which will pass control back to the main part of the program. Also, to meet other conditions, of course conditional statements can be added to accompany the control structures: case statement and possible while loop.

    Example of using a case statement to fulfill your request

    #! /bin/sh 
    
    # For potential users of BSD, or other systems who do not
    # have a bash binary located in /bin the script will be directed to
    # a bourne-shell, e.g. /bin/sh
    
    # NOTE: It would seem best for handling user entry errors or
    # exceptions, to put the decision required by the input 
    # of the prompt in a case statement (case control structure), 
    
    echo Would you like us to perform the option: "(Y|N)"
    
    read inPut
    
    case $inPut in
        # echoing a command encapsulated by 
        # backticks (``) executes the command
        "Y") echo `Do something crazy`
        ;;
        # depending on the scenario, execute the other option
        # or leave as default
        "N") echo `execute another option`
        ;;
    esac
    
    exit
    

提交回复
热议问题