0

So I have the following bash script aliased as "fortunes":

#!/bin/bash -i
REPLY=;
history -w /tmp/fortunes_history_backup; # save history ...
history -c; # and clear it.
while [ ! \( "$REPLY" = "q" -o "$REPLY" = "quit" -o "$REPLY" = "exit" \) ];
do
    clear;
    if [ -n "$REPLY" ]; then
        history -s $REPLY; # store command in history
    fi
    (fortune -c $REPLY;) || (clear; fortune -c;)  # try to use the command as fortune file; 
                                                  # if that file can't be found, use a random one
#    echo `history -p !-1`;
    read -e;
done
history -r /tmp/fortunes_history_backup # restore history

the relevant part is:

  • I backup the history
  • then I clear it
  • then, each time the user enters something, I add it to the history
  • when I'm finished, I restore the old history.

What I now want to happen is that the user can navigate through his history inside this script with the arrow keys, just like in normal bash.

history -p !-1 (get latest entry), history -w, history -c and history -r all work as expected; however, pressing the arrow keys while the script is running doesn't do anything.

(Before I had the history commands, it would cycle through my bash history previous to running the script.)

Is there some way to make this work?

(What I suspect is happening is that the bash doesn't update the history until the script finishes, which would mean there's no solution...)

1 Answer 1

1

I got it to work by

  • creating a clear history file
  • appending each history command to that file, and then
  • reloading the history from that file each time a command was added:

(blank line to fix markdown)

#!/bin/bash -i
REPLY=;
backupFile=/tmp/fortunes_history_backup;
tmpFile=/tmp/fortunes_history;
echo -n > $tmpFile; # clear the temporary history file
history -w $backupFile; # save history ...
history -c; # and clear it.

while [ ! \( "$REPLY" = "q" -o "$REPLY" = "quit" -o "$REPLY" = "exit" \) ];
do
    clear;
    if [ -n "$REPLY" ]; then
        echo $REPLY >> $tmpFile;
        history -r $tmpFile
        # history -s $REPLY does not work!
    fi
    (fortune -c $REPLY) || (clear; fortune -c;)  # try to use the command as fortune file; 
                                                 # if that file can't be found, use a random one
    read -e;
done
history -r $backupFile; # restore history

The essential commands are echo $REPLY >> $tmpFile; history -r $tmpFile;.

I'd still be thankful for any explanation as to why history -s $REPLY; doesn't work (it does outside the script); it feels almost like a bug, but at the same time finding a bug in bash (the bash!) seems almost like hubris :D

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .