简体   繁体   中英

Can I make tab-completion filter files by extension?

Assume myprogram only consumes *.data files as command line arguments. In terminal, when we do

$ myprogram <tab>

we want only the *.data files to be listed for tab auto-complete. How is this behavior achieved? The shell being used is Bash.

Option 1

Type the following into your bash shell

complete -f -X '!*.data' myprogram

the -f option tells complete to only complete based on file names, not directories. the -X option allows you to specify the filter pattern.

Option 2

Note: This solution is global. It will affect tab-completion in every directory and on every command (meaning things like cd or rm , as well as myprogram ). It works by allowing you to specify file extensions that will not appear in tab-complete. This is not exactly what you asked for, but if there aren't many files other than *.data in your working directory, excluding all the options won't be too much of a pain. For both these reasons this option is probably not what you want but it is still worth noting.

In the file ~/.bash_profile add the line

FIGNORE=".py:.txt:.out:.exe:.c:<etc>"

The syntax there is to create a colon-separated list of the file extensions you want to ignore. After saving the new .bash_profile you must type . ~/.bash_profile . ~/.bash_profile for the changes you made to take effect.

Further info

For more info about the complete command check out Programmable Completion Builtins in the Bash manual.

Better use _filedir instead of "raw" complete .

Justification

  • grep _filedir -r $(pkg-config --variable=completionsdir bash-completion) | wc -l
  • tilde ( ~ ) paths are being expanded
  • Prefixes are removed for directories, ie for /home/tux/Do<TAB><TAB> , the list you get as a reply removes '/home/tux' and is thus much more compact
  • Easier to implement and more failsafe

MWE

Write a file "completions/myprogram", which you source by . completions/myprogram . completions/myprogram . Content:

_myprogram()
{
    # init bash-completion's stuff
    _init_completion || return

    # fill COMPREPLY using bash-completion's routine
    _filedir '@(data)'
}
complete -F _myprogram myprogram

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM