Read a variable in bash with a default value

后端 未结 9 632
不思量自难忘°
不思量自难忘° 2020-11-29 16:13

I need to read a value from the terminal in a bash script. I would like to be able to provide a default value that the user can change.

# Please enter your          


        
9条回答
  •  情深已故
    2020-11-29 17:04

    I found this question, looking for a way to present something like:

    Something interesting happened.  Proceed [Y/n/q]:
    

    Using the above examples I deduced this:-

    echo -n "Something interesting happened.  "
    DEFAULT="y"
    read -e -p "Proceed [Y/n/q]:" PROCEED
    # adopt the default, if 'enter' given
    PROCEED="${PROCEED:-${DEFAULT}}"
    # change to lower case to simplify following if
    PROCEED="${PROCEED,,}"
    # condition for specific letter
    if [ "${PROCEED}" == "q" ] ; then
      echo "Quitting"
      exit
    # condition for non specific letter (ie anything other than q/y)
    # if you want to have the active 'y' code in the last section
    elif [ "${PROCEED}" != "y" ] ; then
      echo "Not Proceeding"
    else
      echo "Proceeding"
      # do proceeding code in here
    fi
    

    Hope that helps someone to not have to think out the logic, if they encounter the same problem

提交回复
热议问题