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

后端 未结 30 1712
不思量自难忘°
不思量自难忘° 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条回答
  •  -上瘾入骨i
    2020-11-22 05:00

    Yes / No / Cancel

    Function

    #!/usr/bin/env bash
    @confirm() {
      local message="$*"
      local result=''
    
      echo -n "> $message (Yes/No/Cancel) " >&2
    
      while [ -z "$result" ] ; do
        read -s -n 1 choice
        case "$choice" in
          y|Y ) result='Y' ;;
          n|N ) result='N' ;;
          c|C ) result='C' ;;
        esac
      done
    
      echo $result
    }
    

    Usage

    case $(@confirm 'Confirm?') in
      Y ) echo "Yes" ;;
      N ) echo "No" ;;
      C ) echo "Cancel" ;;
    esac
    

    Confirm with clean user input

    Function

    #!/usr/bin/env bash
    @confirm() {
      local message="$*"
      local result=3
    
      echo -n "> $message (y/n) " >&2
    
      while [[ $result -gt 1 ]] ; do
        read -s -n 1 choice
        case "$choice" in
          y|Y ) result=0 ;;
          n|N ) result=1 ;;
        esac
      done
    
      return $result
    }
    

    Usage

    if @confirm 'Confirm?' ; then
      echo "Yes"
    else
      echo "No"
    fi
    

提交回复
热议问题