Read a variable in bash with a default value
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 name: Ricardo^
In this script the prompt is "Please enter your name: " the default value is "Ricardo" and the cursor would be after the default value. Is there a way to do this in a bash script?
You can use parameter expansion, e.g.
read -p "Enter your name [Richard]: " name
name=${name:-Richard}
echo $name
Including the default value in the prompt between brackets is a fairly common convention
What does the :-Richard
part do? From the bash manual:
${parameter:-word}
If parameter is unset or null, the expansion of word is substituted. Otherwise, the value of parameter is substituted.
Also worth noting that...
In each of the cases below, word is subject to tilde expansion, parameter expansion, command substitution, and arithmetic expansion.
So if you use webpath=${webpath:-~/httpdocs}
you will get a result of /home/user/expanded/path/httpdocs
not ~/httpdocs
, etc.
read -e -p "Enter Your Name:" -i "Ricardo" NAME
echo $NAME
Notes:
- This option requires bash 4 or higher (
bash --version
) - On macos, install current
bash
using homebrew - brew.sh -
-e
and-i
work together:-e
usesreadline
,-i
inserts text usingreadline
-
bash 4+ manual page for
read
- linuxcommand.org