I have a program that can accept a large number of valid arguments. Many of these have common prefixes and are in a directory tree structure. The options often do not exist and some directories can be used with or without the slash but some can only be used without the slash.
If I already have bash completion that shows me this list of alternatives and changes the commandline as I press and partially complete an argument as below:
$ myprog <TAB><TAB>
foo
somedirectory/a
somedirectory/b
somedirectory/c
zibble
zibble/a
zibble/b
zibble/c
$ myprog so<TAB>
$ myprog somedirectory<TAB><TAB>
somedirectory/a
somedirectory/b
somedirectory/c
$ myprog somedirectory/<TAB><TAB>
a
b
c
How do I change it for bash completion that does this like regular file/dir completion:
$ myprog <TAB><TAB>
foo
somedirectory/
zibble
zibble/
$ myprog so<TAB>
$ myprog somedirectory/<TAB><TAB>
a
b
c
and
$ myprog <TAB><TAB>
foo
somedirectory/
zibble
zibble/
$ myprog zi<TAB>
$ myprog zibble<TAB><TAB>
zibble
zibble/
$ myprog zibble/<TAB><TAB>
a
b
c
The key is to add this line just before returning completions for the the word that should behave like directory completion:
[[ $COMPREPLY == */ ]] && compopt -o nospaceBy running this after compgen the only suggestions in the COMPREPLY array match the current word being completed. If there is more than one suggestion it will only be partially completed and no space will be added (standard behaviour). If there is only one suggestion then it is used to decide whether to add a space.
Now if you trim all the filenames under zibble/ bash will not add a space separator when it figures out that zibble/ is the only match for the word being completed.
Here’s a patch against the bash completion of debian http://anonscm.debian.org/gitweb/?p=bash-completion/bash-completion.git – so there is some weird stuff in the patch context.
It applies cleanly against this version using the git apply command of the “git” version control program: http://anonscm.debian.org/gitweb/?p=bash-completion/bash-completion.git;a=commit;h=2897e62fe7e535eb048f7e08f03ac3fbc3a84fa5