简体   繁体   English

具有bash可编程完成的条件尾随空间

[英]Conditional trailing space with bash programmable completion

I'm creating a function to provide programmable completion for a command that I use (with much help from http://www.debian-administration.org/articles/317 ). 我正在创建一个函数来为我使用的命令提供可编程完成功能(在http://www.debian-administration.org/articles/317的帮助下)。 The shell script usage is as follows: shell脚本用法如下:

script.sh command [command options]

where command can be either 'foo' or 'bar' and command options for 'foo' are 'a_foo=value' and 'b_foo=value' and command options for 'bar' are 'a_bar=value' and 'b_bar=value'. 其中command可以是'foo'或'bar','foo'的命令选项是'a_foo = value'和'b_foo = value','bar'的命令选项是'a_bar = value'和'b_bar = value' 。

Here's the configuration I'm using: 这是我正在使用的配置:

_script() {
  local cur command all_commands                                                                    
  COMPREPLY=()
  cur="${COMP_WORDS[COMP_CWORD]}"
  command="${COMP_WORDS[1]}"
  all_commands="foo bar"
  case "${command}" in
    foo)
      COMPREPLY=( $(compgen -W "--a_foo --b_foo" -- ${cur}) ); return 0;;
    bar)
      COMPREPLY=( $(compgen -W "--a_bar --b_bar" -- ${cur}) ); return 0;;
    *) ;;
  esac
  COMPREPLY=( $(compgen -W "${all_commands}" -- ${cur}) )
  return 0
}

complete -F _script script.sh

This mostly works as I'd like: 这主要是按照我的意愿行事:

% script.sh f[TAB]

completes to: 完成:

% script.sh foo 

(with a trailing space as desired) (根据需要设有尾随空格)

However, this: 但是,这个:

% script.sh foo a[TAB]

completes to: 完成:

% script.sh foo a_foo 

(also with a trailing space) (也有尾随空格)

I'd like to replace the trailing space with an '='. 我想用'='替换尾随空格。 Alternatively, I'd be willing to change the values passed to compgen to be "--a_foo= --b_foo=", in which case I could just delete the trailing space. 或者,我愿意将传递给compgen的值更改为“--a_foo = --b_foo =”,在这种情况下,我可以删除尾随空格。

Unfortunately, the command is not under my control, so I can't change the command line options to be of format "--a_foo value" instead of "--a_foo=value". 不幸的是,该命令不在我的控制之下,因此我无法将命令行选项更改为格式为“--a_foo value”而不是“--a_foo = value”。

First you need to add = to the COMPREPLY: 首先,您需要将=添加到COMPREPLY:

COMPREPLY=( $(compgen -W "--a_foo= --b_foo=" -- ${cur}) )

next you need to tell completion not to add space after = with 接下来你需要告诉完成不要在=后添加空格

compopt -o nospace

So, you script lines should be: 所以,你的脚本行应该是:

foo)
  COMPREPLY=( $(compgen -W "--a_foo= --b_foo=" -- ${cur}) ); compopt -o nospace; return 0;;
bar)
  COMPREPLY=( $(compgen -W "--a_bar= --b_bar=" -- ${cur}) ); compopt -o nospace; return 0;;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM