hookenz
hookenz

Reputation: 38917

How is tab completion implemented for linux commands?

I've noticed that sometimes commands can be tab completed.

e.g. the xm command in xen.

you type xm[space][tab] and it prints out the valid options which are:

addlabel        destroy         info            network-attach  resume          sysrq           vnet-delete
block-attach    dmesg           labels          network-detach  rmlabel         top             vnet-list
block-detach    domid           list            network-list    save            trigger         vtpm-list
block-list      domname         loadpolicy      new             sched-credit    unpause         
cfgbootpolicy   dry-run         log             pause           sched-sedf      uptime          
console         dump-core       makepolicy      reboot          serve           vcpu-list       
create          dumppolicy      mem-max         rename          shutdown        vcpu-pin        
debug-keys      getlabel        mem-set         resources       start           vcpu-set        
delete          help            migrate         restore         suspend         vnet-create 

That's pretty slick!

How can I implement my own tab command completion in Linux?

Upvotes: 8

Views: 12838

Answers (4)

Cascabel
Cascabel

Reputation: 497012

This is a pretty broad question, but the general idea is that you register something with the either the compgen or complete builtin. They're both documented in the manual. The previous section documents the general topic of programmable completion, going through how completion attempts are processed.

For a whole ton of examples, see /etc/bash_completion, which provides all the default completion that comes with bash (beyond the totally built-in stuff like filename completion). For even more examples, see anything in /etc/bash_completion.d; those are automatically sourced by /etc/bash_completion as a way of extending the default completion.

Upvotes: 10

mrb
mrb

Reputation: 3330

bash's smart completion is handled by a series of scripted bash functions. On Debian, probably Ubuntu, and maybe other Linux distributions, you can find your system's installed completions in /etc/bash_completion.d.

The official documentation on this mechanism is at http://www.gnu.org/software/bash/manual/bash.html#Programmable-Completion

Upvotes: 1

SiegeX
SiegeX

Reputation: 140397

This is done via the shell through the use of the GNU Readline library in the case of bash

Upvotes: 1

Related Questions