bash autocompletion with file names

2019-07-04 04:44发布

I can't get a simple bash autocompletion function to work. I need to autocomplete file names from a predefined directory so it will look like this:

$ cmd log<TAB><TAB>
file1.log file2.log file3.log   

Where files are from /var/log/app.

3条回答
闹够了就滚
2楼-- · 2019-07-04 05:00

I found this to work as needed:

COMPREPLY=( $(compgen -W "$(ls /var/log/app/)" -- $cur) )

Thanks to dogbane in https://unix.stackexchange.com/questions/28283/autocomplete-of-filename-in-directory !

查看更多
一夜七次
3楼-- · 2019-07-04 05:02

Put them into ~/.bashrc

_cmd() { COMPREPLY=($(ls /var/log/app)); }    
complete -F _cmd cmd

To write a full-featured auto-complete function,
please take a look at /etc/bash_completion.d/python.

查看更多
叼着烟拽天下
4楼-- · 2019-07-04 05:18

I don't see the point of using ls when the shell can list files just fine by itself, so here's one using just the shell.

_cmd() {
    local files=("/var/log/app/$2"*)
    [[ -e ${files[0]} ]] && COMPREPLY=( "${files[@]##*/}" )
}
complete -F _cmd cmd
查看更多
登录 后发表回答