1

I am writing a script that takes a lot of user input, then creates a file from that input. Some of the inputs are fairly repetitive, and so I would like to enable the up arrow functionality to include the strings that have already been put in. I am having difficulty finding out how to do this.

I have tried

set -o history

but that only gives me the actual commands run, and not the inputs that have been received. I also know that

"\e[A" 

is the up arrow command, but this is as far as I have gotten. A test script is as follows:

#!/bin/bash

set -o history

read -e date
read -e date2
read -e date3

echo $date $date2 $date3

After inputting $date I would like to be able to up arrow and get the contents of $date to use for $date2. Any ideas?

1 Answer 1

3

You can try to play with this little snippet:

#!/bin/bash

HISTFILE=myhistoryfile
history -r
for i in {1..3}; do
   read -ep "Enter date $i: " d
   history -s "$d"
done
history -w
echo "Thanks for using this script. The history is:"
history

We define the file to be used as history file: myhistoryfile and load it into memory with history -r. Then we enter the loop and after each user input in variable d we perform

history -s "$d"

to append the input d to current history. At the end of the loop we perform

history -w

to actually write that to the history file.

Try different combinations: with/without history -s or history -w to understand what they really do. And read the manual!

1
  • 1
    This worked. I had that manual pulled up, but I didn't see the -s command. Commented Apr 30, 2014 at 13:23

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