How do I tell bash autocompletion that the colon separates the switch from the value?

StackOverflow https://stackoverflow.com/questions/23313747

  •  10-07-2023
  •  | 
  •  

I have a program which uses switches in the form:

/path/to/binary --foo:on|off --bar:opt1|opt2|opt3 --path:filename

I have been able to create a bash autocompletion file which adds the --foo or --bar switches, but I can't seem to add detection on the previous used switch to complete the on|off because the colon is not recognised by bash as a split character between the switch and its value. Bash autocompletion works fine if I make it accept --foo on|off using a space, but unfortunately the program requires the colon and the completion with the space will be incorrect.

Can this be fixed modifying somehow COMP_WORDBREAKS? I can't see any example in the man page to do this.

有帮助吗?

解决方案

Your completion should act as though binary takes not an option --foo with an argument of on or off, but two separate options --foo:on and --foo:off, because that's exactly what binary takes.

For non-constant options, such as your --path:foo/bar example, perhaps something like

cur=${COMP_WORDS[COMP_CWORD]}

case $cur in
    --path:*)
      IFS=: read opt partialFile
      for f in $(compgen -f $partialFile); do
          COMPREPLY+=( "--path:$f" )
      done
      ;;

I realize this won't work well with file names containing whitespace or other special characters, but then I'm not sure how programmable completion deals with them in the first place.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top