[Bash] Read History function & Read Arrowkeys

Hi.

How can I create a history function? (By "read" command or so)
&
How can I configure a read command so that the arrow keys are not displayed so funny? (^[[A)

Thanks in advance.

Bash has an -e option to read to support READLINE functionality (emac/vi editing, history, etc)

So try:

read -e -p "Enter your name: " name

To add responses to the history use history -s <response>

Example:

# Clear history
history -c

while true
do
    read -e -p "Enter your name (QUIT when done):" name
    #Save name into history
    history -s "$name"
    [ "$name" = "QUIT" ] && break
    echo "Hello, $name"
done

This history can also be written out to a file (for later invocations of your script) with history -w <filename> and read back in from a file with history -r <filename>

How can I save it in your own history file?

You can save the history to a file (say .username.history) with this command:

history -w $HOME/.username.hist

To read history back use:

history -r  $HOME/.username.hist

So our example username prompting script would do this:

HISTFILE=$HOME/.username.hist
# Clear history
history -c

# If previous history exists load it in now
[ -f "$HISTFILE" ] && history -r "$HISTFILE"

while true
do
    read -e -p "Enter your name (QUIT when done):" name
    #Put name into history
    history -s "$name"
    [ "$name" = "QUIT" ] && break
    echo "Hello, $name"
done

# Save history for next time we run script
history -w "$HISTFILE"

Thanks :slight_smile: