Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

How can I make the builtin read command support history, by pressing the up/down key to cycle through them?

I've tried catching when you press the up key, however it doesn't seem to work with read:

read -p '> ' -n 3 foo
echo -n "$foo" | hexdump

Pressing the arrow keys seems to work and I can detect it using this, however if I press aa, it will fail as it will only read the first character of the identifier of the up-arrow, while the third is needed to distinguish the different arrow keys.

share|improve this question
up vote 8 down vote accepted

You can use rlwrap for this, if you don't mind installing software.

You'll probably want to keep a separate history file that only maintains history for the particular prompt in your script (ie. avoid mixing with the user's shell command history).

Here's an example that might work for you:

# Save in rlwrap_example.sh

USERINPUT=$(rlwrap -H $HISTORY sh -c 'read REPLY && echo $REPLY')
echo "User said $USERINPUT"

$ ./rlwrap_example.sh
User said hello

In the above script, the user can use all GNU readline functionality, with history served from — and stored in — ~/.myscript_history. Tweak as needed.

Alternatively, you can use bash's read -e, which enables readline for read invocations, but you will probably find its history functionality too limited (ie. almost nonexistent).

share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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