Displaying default values when accepting input from user

Is there a way to display the default answer when accepting input from the user in the unix script..

e.g.
ans="n"
read $ans?"Enter y to continue n to exit:"

altough ans contains n the message doesn't display the current contents on ans .. you get

Enter y to continue n to exit:

You could try printing the default and then backup over it. tput will give the the move cursor left escape sequence.

BACK="$(tput cub1)"
ans=y
echo -e "Enter y to continue n to exit: $ans$BACK\c" ; read ans
1 Like

perfect .. thanks very much .....

@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"

nope, chubler's solution works perfectly for me ..

thanks

On which Operating system and shell do you use ?

AIX 6.1

I ran my test on SunOS :wink:

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