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

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

    You can use the built-in read command ; Use the -p option to prompt the user with a question.

    Since BASH4, you can now use -i to suggest an answer :

    read -e -p "Enter the path to the file: " -i "/usr/local/etc/" FILEPATH
    echo $FILEPATH
    

    (But remember to use the "readline" option -e to allow line editing with arrow keys)

    If you want a "yes / no" logic, you can do something like this:

    read -e -p "
    List the content of your home dir ? [Y/n] " YN
    
    [[ $YN == "y" || $YN == "Y" || $YN == "" ]] && ls -la ~/
    

提交回复
热议问题