Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

bash script: How to implement your own history mechanism?

I'm implementing an interactive bash script similar to the MySQL client, /usr/bin/mysql. In this script I need to issue various types of 'commands'. I also need to provide a history mechanism whereby the user can use the up/down arrow keys to scroll through the commands entered so far.

The snippet listed here (Example 15-6, Detecting the arrow keys) does not exactly do what I want it to. I really want the following:

  1. The up/down arrow keys should operate in silent mode. Meaning, they should not echo their character codes on the terminal.

  2. The other keys however (which will be used to read the command names and their arguments) must not operate in silent mode.

The problem with read -s -n3 is that it does not satisfy my simultaneously conflicting requirements of silent mode and echo mode, based solely on the character code. Also, the value -n3 will work for arrow keys but, for other/regular keys, it won't 'return control' to the calling program until 3 characters have been consumed.

Now, I could try -n1 and manually assemble the input, one character at a time (yuck!). But the character-code based silent-/echo-mode switching problem would still persist!

Has anyone attempted this thing in bash? (Note: I cannot use C, nor other scripting languages like Perl, Python, etc.)

EDIT

Continuing with Dennis' answer... You will also need to manually add your desired entries to your history via history -s, like so...

while read -e x; do
    history -s "$x"
    # ...
done
like image 997
Harry Avatar asked Feb 15 '11 12:02

Harry


1 Answers

You can use read -e to have read use readline. It will process your cursor keys and maintain the history for you. You will also need to manually add your desired entries to your history via history -s, like so:

while read -e x; do
    history -s "$x"
    # ...
done
like image 118
Dennis Williamson Avatar answered Oct 02 '22 07:10

Dennis Williamson