Saturday, October 09, 2010

Bash Auto-Completion Trick

Most of us who use the bash shell in *nix environments, often find the Tab-key auto-completion to be a very helpful timesaver. But one of the main problems is that he feature is not adaptive, i.e. it does nothing to learn from my previous commands. For example in my home directory I have two folders: “picture” and “programming”. Usually there is no reason for me to traverse the “picture” folder using bash, I’d rather use nautilus for that. So when I type something like “cd p” and press Tab, I would ideally like to get “programming” rather than “picture”. What if we could somehow use the history of commands to help this auto-complete feature?

Here is a cool bash trick that I have been using for quite sometime. It helps me search the history of typed commands that begin with what I have typed so far. Here is the way to enable it in your system.

Edit the “~/.inputrc” file by appending the following lines to it and save it:

"\e[5~": history-search-backward
"\e[6~": history-search-forward

Note that the file “~/.inputrc” might not be present in your system, so in that case you will have to create it.

Now to use this feature, open a new instance of the shell and type something like “cd p” and press the PageUp and PageDown keys to search the history of commands that begin with “cd p” backwards or forwards and cycle through them.

Personally I find this quite a time saver. However note that the completion feature is not directory aware, so like in the previous example it might just give you the name of a directory that does not exist in your current path.

5 comments:

  1. A similar type of concept already exists with bash. Using Alt+TAB (obviously it will not work under gnome or KDE if you have kept the default settings of changing the window with Alt+TAB) See here http://www.softpanorama.org/Scripting/Shellorama/command_completion.shtml.

    Any ideas about how it can be implemented to be directory aware?

    ReplyDelete
  2. @Devlina, Thanks

    @myt, I rarely use Linux in CLI. But thanks for the info. Implementing directory aware predictions would require restructuring the implementation of "history" command. Along with the commands, "history" would also have to story the complete path in which the command was called. You have any better ideas?

    ReplyDelete
  3. Here's a nice link for getting some other keys to work like Home, End, Del, Bksp ... http://www.ibb.net/~anne/keyboard.html

    ReplyDelete
  4. Here is another link for bash tips and tricks:
    http://www.ukuug.org/events/linux2003/papers/bash_tips/

    Writing the history is the best one that I liked.

    ReplyDelete

I'd love to hear from you !