Viper Bailey
Viper Bailey

Reputation: 12027

compgen does not descend into directories

I have defined a bash_completion script. There are certain cases in which I want to fallback to the basic file-based completion that happens by default for most commands. To do this I am using compgen, but I can't get it to descend into sub-directories.

Imagine I am running compgen from within a directory that contains a directory called bin. When I run compgen -f bi I am given bin. I would expect this to return bin/ which would then permit me to push TAB again to descend into the contents of the bin directory. But instead, complete gets just one value and assumes that it has reached the end of processing. This differs from how bash completion seems to work in general where ls bi[TAB] would result in ls bin/.

Since I can't get this to work, for the time being I have written custom code that descends into the directories to perform the correct bash completion, but there must be a way to do this with compgen directly.

Upvotes: 1

Views: 584

Answers (1)

FNX
FNX

Reputation: 16

Been bashing my head against this brick wall (no pun intended). Just realised that the trick is not in how you invoke compgen in your custom completion function, but how you tell complete to handle it, in particular you need to tell it to treat the results from your function as filenames (and thus if a directory is given, to let you descend into it):

complete -o filenames -F _mycmd_completions mycmd

Internally to my custom function, also, I am doing basically the following to match dirs and files (inc. handling for files/dirs with spaces):

_mycmd_completions()
{
  local IFS=$'\n\t'
  local word="${COMP_WORDS[$COMP_CWORD]}"
  local values=($(compgen -d -- "$word") $(compgen -f -- "$word"))
  # Processing on values ...
  COMPREPLY=(${values[@]})
}

Upvotes: 0

Related Questions