Bash Autocompletion

From SlackWiki
Jump to: navigation, search


Did you know that Bash has a really powerful autocompletion system, which can and usually will make your life easier? If you have used ZSH, you probably know what I'm talking about.

For example, you can type

  svn co<TAB><TAB>

and bash will attempt to auto complete as it does normally with paths and variables, but instead it will output:

 ismael@damned_02:~/src/chkout$ svn co<TAB><TAB>
 co      commit  copy    
 ismael@damned_02:~/src/chkout$ svn co

Then you can type:

 ismael@damned_02:~/src/chkout$ svn com<TAB>

and BASH will auto complete to:

 ismael@damned_02:~/src/chkout$ svn commit

Or if you're running as root and want to get rid of that *$@& module wich keeps crashing your machine:

  root@damned_02:~# rmmod n<TAB>
  root@damned_02:~# rmmod nvidia


If you think all that is neat, all that you have to do to enable this kind of auto completion in Slackware is to install the bash-completion package, which can be found under /extra:

  root@damned_02:~# mount /mnt/cdrom
  root@damned_02:~# installpkg /mnt/cdrom/extra/bash-completion/bash-completion-20060301-noarch-1.tgz
  ...

(BTW, bash-completion also autocompletes installpkg, upgradepkg and removepkg with .tgz files and installed packages for removepkg. It can also fill mount commands with data from fstab).

Then you can just logout and login again or

  source /usr/share/bash-completion/bash_completion

and voila!


You can see which commands have autocompletion by issuing:

 complete -p | sed -e's/.* \([^ ]\+\)/\1/' | sort | less

You can also add your own commands at /etc/bash_completion.d/ You may want to see the available completions to understand how they work.

For your own personal user account you can edit your ~/.bash_completion file.

Here is a sample BASH completion function I made to give the script 'test' 3 completion options:

_test ()
{
         local cur
         cur=${COMP_WORDS[COMP_CWORD]}

         if [[ "$cur" == -* ]]; then
         COMPREPLY=( $( compgen -W '-option -test -foobar' -- $cur ))

         else
             _filedir
         fi
}

complete -F _test test

I put that into my ~/.bash_completion file and now

 $ test -<tab>
 -foobar  -option  -test

brings up those three options (-option,-test and -foobar). You have to reload your terminal first to see the changes or re-source /etc/bash_completion

 $ . /usr/share/bash-completion/bash_completion

or just re-source your ~/.bash_completion

 $ . ./.bash_completion