I am trying to invoke bash completion twice for a script. The first completion will be a user pre-filtered by grep, the second is a directory. I wrote a small simplified test script.
I managed to get the user completion, but not the second completion for the directory. The second completion starts correctly when I press tab, but always reverts back to the base directory (/tmp in the example below) instead of completing.
I tried multiple approaches which I found on here and on google, to add a second completion with a directory. But either could not make it work at all, or got the result described above. I also tried adding _filedir(), as suggested in stackflow-answer, but could not make it work.
My preference, is to have /tmp with the first tab for the second completion and then get only the subdirectories of tmp displayed. In the final version I need only one completion for a directory X (/tmp/X) and no further decent should be allowed.
_b_complete()
{
COMPREPLY=()
if [ $COMP_CWORD -eq 1 ]; then
COMPREPLY+=($(compgen -W "$(compgen -u | grep f)" "${COMP_WORDS[1]}"))
elif [ $COMP_CWORD -eq 2 ]; then
COMPREPLY+=($(compgen -d -- "/tmp/"))
fi
return
}
complete -F _b_complete b
################### The following code is working ########################
This code is working based on pynexj answer:
_foo_complete()
{
local cmd=$1 cur=$2 pre=$3
COMPREPLY=()
if [ $COMP_CWORD -eq 1 ]; then
COMPREPLY+=($(compgen -W "$(compgen -u | grep f)" "${COMP_WORDS[1]}"))
elif [ $COMP_CWORD -eq 2 ]; then
if [[ $cur != /tmp/* ]]; then
COMPREPLY=( /tmp/{,_} )
elif [[ $cur != /tmp/*/* ]]; then
COMPREPLY=( $( compgen -d "$cur" ) )
fi
fi
}
complete -F _foo_complete foo