Skip to content

Bash Autocomplete


A  great feature of Bash, but rather arcane, is its auto-complete function. A function that is very customizable and expandable. Bash not only offers some off-the-shelf ready features for auto-completion, but it allows anyone to expand this list in any way she/he wishes.

Unfortunately, Bash‘s manual is not very helpful. Since it references only the interfaces, it doesn’t give many hints on how to use these features or giving any helpful examples. Nevertheless, I found a great article, where many of these features are explained in a well understood and simple language.

The most important builtin for auto-completion seems to be `complete‘. In this first in the series article, the author gives an introduction to Bash‘s feature and he also gives a description of the function of complete -p (I think it produces the same results as simply typing complete): it prints all the known to Bash auto-complete functions.

Basically, using complete one can associate auto-complete functions and operations with commands. For example, I wanted to auto-complete a specific pattern of filenames while using a custom command, pdf7z. I found myself using this command with files starting with an underscore and ending with .7z extension.

It seems, that this is the most basic function one can implement in Bash with the complete keyword:

   complete -G '_*.7z' pdf7z

We can test this function by typing this command in a new shell and then trying to execute the pdf7z command by pressing the TAB key for completing the filename. Auto-complete is so great as a feature that pdf7z command doesn’t even need to exit in order to check that the completion is correct! Of course, after finding out which exactly is the appropriate complete command, we can put the final code in a file lying at /etc/bash_completion.d/ (every file in there is sourced automatically by Bash at startup), or have this line of code at our own startup script (.bashrc, .bash_profile, or something else).

This is a rather simplistic and naive approach, yet it works! In the second article on the series, the author gives more examples on using complete for more advanced functions, as auto-completing command arguments. But these operations are rather complicated and I might re-deal with this subject in the future. Bash‘s auto-complete is truly a very strong and powerful tool in our arsenal!

From → Administration, Shell

Leave a Comment

What do you think?

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: