5

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

10

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.

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)

| improve this answer | |
  • 1
    -bash: read: -i: invalid option read: usage: read [-ers] [-u fd] [-t timeout] [-p prompt] [-a array] [-n nchars] [-d delim] [name ...] – Flo Nov 4 '14 at 19:20
  • Your version of bash? Are you using bash or /bin/sh ? – glenn jackman Nov 4 '14 at 19:49
  • GNU bash, version 3.2.53(1)-release (x86_64-apple-darwin14) – Flo Nov 4 '14 at 20:11
0

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"
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.