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
I've just used this pattern, which I prefer:
read name || name='(nobody)'
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).
read -e -p "Enter Your Name:" -i "Ricardo" NAME
echo $NAME
#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" }'
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
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