4

after hours of search I ended up writing my first stackoverflow question.

I want to create a completion function for a bash script, so far so good ;). This bash script calls other executables that have their own autocompletion.

Example:

$ my_script foo par
  # calls /usr/local/libexec/my_script/foo par

Autocompleting the first parameter of my_script (in this case "foo") works, because the possible options are the files in the folder "/usr/local/libexec/my_script/". Each program in this folder does have a working auto completion, which was a byproduct of using boost::program_options.

I now want to implement the auto completion for the next parameters of my_script by referencing to the auto completion of the program gooing to be called.

$ my_script foo <tab>
  # should output possible options to the foo subcommand
  # like /usr/local/libexec/my_script/foo <tab>

I've started by this answer Bash completion from another completion, but _command or _command_offset 1 does not seem to work for me.

  • How can I get the options of foo, and how can I use this in my_script?

My current /etc/bash_completion.d/my_script looks like the following

_my_script()
{
  local cur prev opts
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  prev="${COMP_WORDS[COMP_CWORD-1]}"

  if [[ "$COMP_CWORD" == 1 ]]; then
    # 1. param: for program to be loaded
    for i in $( ls /usr/local/libexec/my_script/ ); do
      opts="${opts} ${i} "
    done
    COMPREPLY=( $(compgen -W "${opts}" ${cur}) )
  else
    # next param: of the program to be loaded

    # how do I get the options of "foo" here?        

  fi

  return 0
}
complete -F _my_script my_script
dbc
  • 104,963
  • 20
  • 228
  • 340
Tobias
  • 41
  • 1

1 Answers1

0

As soon as I read your question, the completion of sudo and git came to my mind. They both have the similar behavior you desired. So I looked for their completion functions. Here are your missing lines:

local root_command=${COMP_WORDS[0]}
_command_offset 1

It's copied from /usr/share/bash-completion/completions/sudo in Ubuntu 16.04. I totally don't knows its meaning. But it works.

scinart
  • 457
  • 2
  • 9