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
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.
The -e and -t parameter does not work together. i tried some expressions and the result was the following code snippet :
QMESSAGE="SHOULD I DO YES OR NO"
YMESSAGE="I DO"
NMESSAGE="I DO NOT"
FMESSAGE="PLEASE ENTER Y or N"
COUNTDOWN=2
DEFAULTVALUE=n
#----------------------------------------------------------------#
function REQUEST ()
{
read -n1 -t$COUNTDOWN -p "$QMESSAGE ? Y/N " INPUT
INPUT=${INPUT:-$DEFAULTVALUE}
if [ "$INPUT" = "y" -o "$INPUT" = "Y" ] ;then
echo -e "\n$YMESSAGE\n"
#COMMANDEXECUTION
elif [ "$INPUT" = "n" -o "$INPUT" = "N" ] ;then
echo -e "\n$NMESSAGE\n"
#COMMANDEXECUTION
else
echo -e "\n$FMESSAGE\n"
REQUEST
fi
}
REQUEST
name=Ricardo
echo "Please enter your name: $name \c"
read newname
[ -n "$newname" ] && name=$newname
Set the default; print it; read a new value; if there is a new value, use it in place of the default. There is (or was) some variations between shells and systems on how to suppress a newline at the end of a prompt. The '\c' notation seems to work on MacOS X 10.6.3 with a 3.x bash, and works on most variants of Unix derived from System V, using Bourne or Korn shells.
Also note that the user would probably not realize what is going on behind the scenes; their new data would be entered after the name already on the screen. It might be better to format it:
echo "Please enter your name ($name): \c"