0

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
  • here's a simple example: https://pastebin.com/i1WcLGKm – pynexj Sep 29 '22 at 14:36
  • Hi pynexj, thanks for your code example. It is working. I there a way to show only the subdirectories in tmp instead of the hole path /tmp/... ? Would you mind posting your solution here? – user20120789 Sep 30 '22 at 11:17
  • i guess this is what you want: https://pastebin.com/ThumuNue (note that it's not using the `-o nospace` option) – pynexj Sep 30 '22 at 12:35
  • Please provide a precise example of your desired output. Compgen looks like a custom function as well, and it would probably make it easier if I knew what its' definition is. – petrus4 Sep 30 '22 at 14:09

0 Answers0