@Chubler don't know about the behaviour on your or his OS, but your solution would empty the $ans (if just press enter when the cursor is on the y default value)
# BACK="$(tput cub1)"
# ans=y
# echo "Enter y to continue n to exit: $ans$BACK\c" ; read ans
Enter y to continue n to exit: y
# echo "$ans"
#
so i would go for :
read ${ans:=n}?"Enter y to continue n to exit:"
echo "$ans"
# read ${ans:=n}?"Enter y to continue n to exit:"
Enter y to continue n to exit:
# echo "$ans"
n
#
I did put a _ to show where the cursor is
The problem with my code is that it would make the answer appear twice if an input is given...
---------- Post updated at 02:50 PM ---------- Previous update was at 02:18 PM ----------
The final right code is a mix of ours :
BACK="$(tput cub1)"
read ${ans:=n}?"Enter y to continue n to exit: ${ans:=n}$BACK"
It was implied that any code proceeding the prompt treats blank as Y, the question was more around getting the default to be visible on the screen.
A loop that traps illegal entries should probably also be used.
BACK="$(tput cub1)"
while true
do
ans=y
echo -e "Enter y to continue n to exit: $ans$BACK\c" ; read ans
ans=${ans:=y}
case $ans in
[yY]|[Yy][Ee][Ss]) ans=y ; break;;
[nN]|[Nn][Oo]) ans=n ; break ;;
*) echo "Please answer y or n" ;;
esac
done
echo "You answered: $ans"
Edit: Another thought (excersise for reader) is wrap it into a yorn function that prompts with default and sets return code, you can use it like this:
if yorn "Enter y to continue, n to exit" y
then
echo "OK lets go on..."
else
echo "bye bye"
exit
fi