Using read to prompt for editable user input in Bash 3

Below is a simple script to prompt for user input while suggesting an editable default value at the prompt:

shortname=user1

read -e -i $shortname -p "Please enter the username you would like to add: " input
USERNAME="${input:-$shortname}"

Please enter the username you would like to add: user1

The above is the expected and working output in BASH 4

If I try this same code in BASH 3 it doesn't work because this version does not support the "-i" switch.

I need some help getting the same result in BASH 3.
Thanks

A simpler portable way to do the same thing is:

#!/bin/bash
default=user1
printf "Please enter the username you would like to add (%s): " "$default"
read input
USERNAME=${input:-$default}
echo USERNAME is $USERNAME

It should work with any version of bash, ksh, or any other POSIX conforming shell.
The only portable option to the read utility is -r .

Note that I used printf instead of echo because the way you specify printing a prompt without a newline using echo varies from system to system.

Thanks for this code.

Although it's not quite what I'm looking for it's definitely a more portable way of doing things.

The code you proposed results in the following output:

Please enter the username you would like to add to LDAP (user1):

The code I use in BASH 4 results in the following output:

Please enter the username you would like to add: user1

The user name is populated on the editable line already so I can hit enter and accept or hit backspace and make the changes I want.

It's really semantics but It can save a few key strokes.

Hitting enter for the default value is what I tend to see done in these situations.

The other way, beyond bringing an external utility with you, would be to play funny games with the terminal device and handle all keystrokes by yourself:

#!/bin/bash

oldsettings=$(stty -g)

trap "stty $oldsettings" EXIT

readdefault() { # variable prompt default
        local POS="${#3}"
        local VALUE="$3"
        local C

        stty -icanon min 1 time 0 -icrnl -echo

        printf "%s" "$2$3"

        while true
        do
                C="$(dd bs=10 count=1 2> /dev/null)"

                [ -z "$C" ] && continue

                # Okay, you've got raw keystrokes.  Now you're on your own.
        done

        stty icanon
}

readdefault VAR "Enter something:" "qwerty"

I tried filling out more, but could not for the life of me get my terminal and tput to agree on what the 'backspace' key is, even though backspace works in my terminal.

Example partly from here.

You can see why what you're asking for really isn't trivial. It may be more straightforward to upgrade your shell.