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

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

    You want:

    • Bash builtin commands (i.e. portable)
    • Check TTY
    • Default answer
    • Timeout
    • Colored question

    Snippet

    do_xxxx=y                      # In batch mode => Default is Yes
    [[ -t 0 ]] &&                  # If TTY => Prompt the question
    read -n 1 -p $'\e[1;32m
    Do xxxx? (Y/n)\e[0m ' do_xxxx  # Store the answer in $do_xxxx
    if [[ $do_xxxx =~ ^(y|Y|)$ ]]  # Do if 'y' or 'Y' or empty
    then
        xxxx
    fi
    

    Explanations

    • [[ -t 0 ]] && read ... => Call command read if TTY
    • read -n 1 => Wait for one character
    • $'\e[1;32m ... \e[0m ' => Print in green
      (green is fine because readable on both white/black backgrounds)
    • [[ $do_xxxx =~ ^(y|Y|)$ ]] => bash regex

    Timeout => Default answer is No

    do_xxxx=y
    [[ -t 0 ]] && {                   # Timeout 5 seconds (read -t 5)
    read -t 5 -n 1 -p $'\e[1;32m
    Do xxxx? (Y/n)\e[0m ' do_xxxx ||  # read 'fails' on timeout
    do_xxxx=n ; }                     # Timeout => answer No
    if [[ $do_xxxx =~ ^(y|Y|)$ ]]
    then
        xxxx
    fi
    

提交回复
热议问题