Read a variable in bash with a default value

后端 未结 9 595
不思量自难忘°
不思量自难忘° 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 16:55

    I've just used this pattern, which I prefer:

    read name || name='(nobody)'
    
    0 讨论(0)
  • 2020-11-29 16:57

    In Bash 4:

    name="Ricardo"
    read -e -i "$name" -p "Please enter your name: " input
    name="${input:-$name}"
    

    This displays the name after the prompt like this:

    Please enter your name: Ricardo
    

    with the cursor at the end of the name and allows the user to edit it. The last line is optional and forces the name to be the original default if the user erases the input or default (submitting a null).

    0 讨论(0)
  • 2020-11-29 17:00
    read -e -p "Enter Your Name:" -i "Ricardo" NAME
    
    echo $NAME
    
    0 讨论(0)
  • 2020-11-29 17:02
    #Script for calculating various values in MB
    echo "Please enter some input: "
    read input_variable
    echo $input_variable | awk '{ foo = $1 / 1024 / 1024 ; print foo "MB" }'
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-11-29 17:07

    Code:

    IN_PATH_DEFAULT="/tmp/input.txt"
    read -p "Please enter IN_PATH [$IN_PATH_DEFAULT]: " IN_PATH
    IN_PATH="${IN_PATH:-$IN_PATH_DEFAULT}"
    
    OUT_PATH_DEFAULT="/tmp/output.txt"
    read -p "Please enter OUT_PATH [$OUT_PATH_DEFAULT]: " OUT_PATH
    OUT_PATH="${OUT_PATH:-$OUT_PATH_DEFAULT}"
    
    echo "Input: $IN_PATH Output: $OUT_PATH"
    

    Sample run:

    Please enter IN_PATH [/tmp/input.txt]: 
    Please enter OUT_PATH [/tmp/output.txt]: ~/out.txt
    Input: /tmp/input.txt Output: ~/out.txt
    
    0 讨论(0)
提交回复
热议问题