9

How can I use read with something as standard response, which the user can change though? (a default answer)

slhck
  • 228,104
Flo
  • 101

2 Answers2

14

bash version 4+

You would write this:

read -p "enter a value: " -i default -e answer
echo "you answered: $answer"
  • -i default specifies the default answer.
  • -e enables interactive (editing) mode for read. Without this option the default answer does not work.

bash version < 4 (macos has bash 3.x)

So, can't edit the default value with bash 3.2. You could do this:

default="the default value"
read -p "your answer [default=$default] " answer
: ${answer:=$default}
echo "you answered: $answer"

This uses the default value if the user enters nothing (empty string)

glenn jackman
  • 26,306
-1

Reference read - Read a line from standard input:

This is a BASH shell builtin.

One line is read from the standard input, and the first word is assigned to the first name, the second word to the second name, and so on, with leftover words and their intervening separators assigned to the last name.

If there are fewer words read from the standard input than names, the remaining names are assigned empty values.

The characters in the value of the IFS variable are used to split the line into words.

The backslash character `\' may be used to remove any special meaning for the next character read and for line continuation.

If no names are supplied, the line read is assigned to the variable REPLY. The return code is zero, unless end-of-file is encountered or read times out.

Examples

#!/bin/bash
read var_year
echo "The year is: $var_year"

echo -n "Enter your name and press [ENTER]: "
read var_name
echo "Your name is: $var_name"
DavidPostill
  • 156,873