I have noticed that, when I type unzip
in bash and press tab, auto-complete works only on files with .zip extension. How is that done? What if I would like to make program that would accept only image files, how to restrict auto-complete to certain extensions (eg .jpg and .png only).
Is this some kind of system setting or an programming setting that vary for languages (bash, C++, python) ?
Best Answer
The program itself runs whatever file names are passed to it. The restriction to a
.zip
suffix in completion is unrelated to what the program does. Completion is performed by the shell. When you press Tab, the shell parses the command line to some extent looks up the completion rules for the context. Depending on the shell, the context analysis and completion rules may be more or less complex. For example, when the command line containsecho $P
and you press Tab, most shells with completion look for variable names beginning withP
. By default, shells complete file names, because it's a very common case.Bash, tcsh and zsh have ways to make the completion programmable: they parse the command under the cursor, and look up the rules for that particular command in a table. With programmable completion, the entry in the table for the
unzip
program should say that the first argument must be an existing.zip
file, and subsequent arguments must be names of members of the zip archive.The completion rules are not contained in the program itself, but they may be shipped alongside the program in the same package. For example, a package that contains a command
/usr/bin/foo
can contain a file/etc/bash_completion/foo
that describes to bash how to complete arguments for thefoo
command, and a similar file/usr/share/zsh/functions/Completion/_foo
for zsh.