views:

161

answers:

3

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 name: Ricardo^

In this script the prompt is "Please enter your name: " the default value is "Ricardo" and the cursor would be after the default value. Is there a way to do this in a bash script?

A: 
name=Ricardo
echo "Please enter your name: $name \c"
read newname
[ -n "$newname" ] && name=$newname

Set the default; print it; read a new value; if there is a new value, use it in place of the default. There is (or was) some variations between shells and systems on how to suppress a newline at the end of a prompt. The '\c' notation seems to work on MacOS X 10.6.3 with a 3.x bash, and works on most variants of Unix derived from System V, using Bourne or Korn shells.

Also note that the user would probably not realize what is going on behind the scenes; their new data would be entered after the name already on the screen. It might be better to format it:

echo "Please enter your name ($name): \c"
Jonathan Leffler
`printf` is more portable than `echo`
ghostdog74
@ghostdog74: maybe so; those of us who learned shell programming over 25 years ago have a hard time working out which of our practices are still relevant. It increasingly looks like bash has rewritten just about everything. I know printf has been around a while as a command - I very seldom use it, though (probably - never?). I get the impression I should shut up on shell until I've (re)learned bash. 'Tis funny; the software I work on has shell scripts that don't work well - but the trouble isn't bash-isms. I just get fed up with fixing '`if (test -z "$xxx"); ...`' and other C shellisms.
Jonathan Leffler
+2  A: 

you can use parameter expansion eg

read -p "Enter: " name
name=${name:-Richard}
echo $name
ghostdog74
I ended up doing something based on this. Reading into a temp variable `input` and then using `name=${input:-$name}`.
rmarimon
+1  A: 

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).

Dennis Williamson
Can't use bash4 because it is non standard in debian distributions. I need something that will work without much hassle.
rmarimon