Tab completion

Also known as: command-line completion

On this page 7

Tab completion, also called command-line completion, is the shell feature that finishes a partially typed word when the user presses the Tab key, using the commands, file names, options or other values that are valid at that position. In Linux, it is one of the most used interactive features of Bash, Zsh and the Fish shell, and it belongs to the line editor of the shell rather than to the terminal emulator.

Completion saves keystrokes, but its larger value is error prevention: a path that completes is a path that exists, and a command that completes is a command the shell can find on the PATH. Modern completion systems go further and understand the grammar of individual programs, offering subcommands, flags, Git branches or remote host names in context.

How tab completion works inside the shell

Tab completion works by having the line editor intercept the Tab keystroke, inspect the word under the cursor and generate a list of candidates that start with that prefix. In Bash, the line editor is the GNU Readline library; Zsh uses its own editor called ZLE, and the Fish shell ships an integrated editor with built-in suggestions.

The shell first decides what kind of word is being completed. The first word of a command line is completed against aliases, functions, built-ins and executables found in the directories listed in PATH. Later words default to file name completion, while a word starting with a dollar sign is completed against variable names, and a word starting with a tilde is completed against user home directories.

When exactly one candidate matches, the shell inserts it and usually appends a space or a slash. When several candidates match, the shell inserts their longest common prefix; a second Tab press then lists all candidates. This two-step behavior is the default in Bash and can be tuned with Readline variables.

The table below summarizes the default candidate sources by word position.

Word being completedCandidate sourceExample input
First word of a commandAliases, functions, built-ins, executables on PATHsyst completes to systemctl
Later argumentFiles and directories relative to the current directorycat /etc/hos completes to /etc/hosts
Word starting with $Shell and environment variable namesecho $HO completes to $HOME
Word starting with ~User names from the account databasecd ~ro completes to ~root/
Word starting with @Host names, mainly from /etc/hostsssh user@lo completes to a local host
Default completion sources by word position

Programmable completion in Bash and Zsh

Programmable completion lets each command define its own candidates, so that git ch offers checkout and cherry-pick instead of file names. In Bash, the built-in complete command attaches a completion specification to a command name, either as a static word list, a predefined action, or a shell function that fills the COMPREPLY array.

Most Linux distributions install the bash-completion package, which provides hundreds of specifications and loads them lazily on first use from /usr/share/bash-completion/completions. Lazy loading matters because sourcing every script at startup would slow down each new shell noticeably.

Zsh uses a different model called the compsys system, enabled with compinit. Completion functions start with an underscore, live in directories listed in the fpath array, and use helpers such as _arguments that describe options declaratively. Zsh can show descriptions next to each candidate, group candidates by type and navigate them in a menu, which frameworks such as Oh My Zsh enable by default.

The following comparison shows how the main Linux shells implement completion.

ShellCompletion engineDefinition methodNotable strength
BashGNU Readline with programmable completioncomplete and compgen built-ins, shell functionsUbiquitous, large bash-completion collection
ZshZLE with compsysUnderscore functions on fpath, _argumentsMenus, descriptions, fuzzy matching styles
Fish shellBuilt-in editorcomplete command, man page parsingWorks well with no configuration
KornShellBuilt-in editing modesLimited built-in file and command completionLightweight, close to POSIX behavior
Completion systems in common Linux shells

Configuring completion behavior

Completion behavior is configured through Readline variables in Bash and through zstyle settings in Zsh. Bash reads Readline options from ~/.inputrc or /etc/inputrc, and the same options can be set inside .bashrc with the bind built-in, which keeps all interactive settings in one file.

The table lists the Readline options that change everyday behavior the most.

OptionEffect when enabledTypical reason to set it
show-all-if-ambiguousLists matches on the first Tab pressAvoid pressing Tab twice
completion-ignore-caseMatches regardless of letter caseDirectories such as Documents and documents
menu-completeCycles through candidates on each TabBehavior similar to Zsh menus
colored-statsColors candidates by file typeQuicker visual scanning
mark-symlinked-directoriesAppends a slash to linked directoriesConsistent path handling
Frequently used Readline completion options

A user can also write a custom completion for an internal script. A short Bash function that calls compgen -W with a list of subcommands, registered with complete -F, is often enough to make a team tool as discoverable as a system command.

Tab completion is often confused with globbing, history search and autosuggestions, but each feature resolves text at a different moment and from a different source. Completion edits the command line before execution, whereas globbing expands patterns such as *.log only when the command runs.

FeatureTriggerSource of textWhen it acts
Tab completionTab keyFiles, commands, program grammarWhile editing the line
Pathname expansionWildcards such as * and ?Existing filesAt execution time
Reverse history searchCtrl+RBash historyWhile editing the line
AutosuggestionsTyping, accepted with an arrow keyHistory and completionsContinuously, shown as ghost text
Shell aliasTyping the alias nameAlias definitionsAt execution time
Tab completion and neighboring interactive features

The distinction matters in practice: completing a path shows the exact file that will be used, while a wildcard may silently match more files than intended, which is a classic cause of destructive mistakes with rm.

Limitations and common problems

Tab completion is only as accurate as its completion specification, and several recurring problems have well-known causes. The most frequent symptoms are listed below.

  • Completion falls back to file names for a command such as systemctl: the bash-completion package is missing, or the shell is not interactive.
  • Noticeable delay after Tab: the specification queries a slow source, such as a package database, a remote host over SSH or a large Git repository.
  • Completion missing after sudo: the specification for sudo must forward the remaining words to the target command, which bash-completion provides.
  • Different results on servers: minimal container images and rescue systems often ship without completion scripts, so behavior differs from a workstation.
  • Stale command list: Bash caches executable locations, and hash -r clears the cache after software is installed or moved.

Completion also has a security dimension. Completion functions are ordinary shell code that runs with the user’s privileges, so scripts should come from trusted packages, and remote completions should not expose sensitive host or file names on shared screens.

A non-technical view

Tab completion works like the word suggestions on a phone keyboard, but with one difference: it only suggests things that really exist. Type the first few letters of a file or a command, press Tab, and the computer fills in the rest.

If several names start the same way, a second press shows the choices. The main benefit is not speed alone. Because the computer fills in only real names, typing mistakes in long folder names largely disappear.

A concrete example

A system administrator needs to inspect a log file in /var/log/nginx/ on a web server and then restart a service. Instead of typing the full path, the administrator types less /var/lo, presses Tab to get /var/log/, types ng and presses Tab again to reach /var/log/nginx/. Two Tab presses then list access.log, access.log.1 and error.log, and typing e plus Tab selects the error log.

Next, the administrator types systemctl res and presses Tab; the bash-completion package offers restart and reset-failed. After restart ng and one more Tab, the unit name completes to nginx.service. The whole sequence takes about 15 keystrokes instead of more than 60, and because every word was completed from real data, the command contains no typing errors in the path or the unit name.