bash autocompletion with file names

∥☆過路亽.° 提交于 2020-01-04 01:06:42

问题


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.


回答1:


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



回答2:


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:


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.



来源:https://stackoverflow.com/questions/10993514/bash-autocompletion-with-file-names

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!