I am trying to create a bash completion script for my command. ls
has the behaviour that I want. I need to get this same behaviour form my command.
This is what I get for ls
$ ls /home/tux/<Tab><Tab>
Downloads Documents Pictures
$ ls /home/tux/Do<Tab><Tab>
Downloads Documents
I.e. bash only shows the next paths relatively, not absolutely (i.e. it does add Downloads
to the completion list, but not /home/tux/Downloads
)
I wanted to write a completion script that works the same way. This is what I have tried.
_testcommand ()
{
local IFS=$'\n'
local cur=${COMP_WORDS[COMP_CWORD]}
COMPREPLY=( $(compgen -o bashdefault -d -- "$cur") )
if [ "${#COMPREPLY[@]}" -ne 1 ]
then
# remove prefix "$cur", so the preview of paths gets shorter
local cur_len=$(echo $cur | sed 's|/[^/]*$||' | wc -c)
for i in ${!COMPREPLY[@]}
do
COMPREPLY[$i]="${COMPREPLY[i]:$cur_len}"
done
fi
return 0
}
complete -o nospace -F _testcommand testcommand
However the result is like this:
$ testcommand /home/tux/<Tab><Tab>
Downloads Documents Pictures
$ testcommand /home/tux/Do<Tab>
Downloads Documents
$ testcommand Do
How can I make my completion not remove /home/tux/
from the command line?
Note: I think I can not add '-f' or '-d' etc. to the complete
call on the bottom. In reality, the completion must, in some cases, also complete words instead of paths.