Getting compgen to include slashes on directories when looking for files

I ran into the same problem. Here’s the workaround I’m using:

  1. Register the completion function with -o default, e.g., complete -o default -F _my_completion.
  2. When you want to complete a filename, just set COMPREPLY=() and let Readline take over (that’s what the -o default does).

There’s a potential problem with this — you might be using COMPREPLY=() to deny completion where it’s not appropriate, and now that won’t work anymore. In Bash 4.0 and above, you can work around this using compopt as follows:

  1. At the top of your completion function, always run compopt +o default. This disables Readline filename completion when COMPREPLY is empty.
  2. When you want to complete a filename, use compopt -o default; COMPREPLY=(). In other words, enable Readline filename completion only when you need it.

I haven’t figured out a full workaround for pre-4.0 Bash, but I have something that works well enough for me. I can describe this if anyone really cares, but hopefully these older Bash versions will soon fall out of common use anyway.

Leave a Comment