4

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.

0

3 Answers 3

3

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 
Sign up to request clarification or add additional context in comments.

1 Comment

Impressive (but inscrutable for the novice) shell coding! The creation and use of files as an array is powerful. Arrays are documented at gnu.org/software/bash/manual/bash.html#Arrays
-1

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.

2 Comments

ls is not necessary and it's not intended to be used that way. _cmd() { COMPREPLY=(/var/log/app/*); }
It does show the list of files in /var/log/app but when I type a letter to narrow the completion choices and then TAB the letter is being deleted and the completion returns to the original file list. See i.imgur.com/9TPMs.gif
-1

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 !

1 Comment

This solution as written here did not work for me, but the solution in the linked question did. It is just a matter of properly setting $cur.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.