使用bash的可编程完成条件尾随空格 [英] Conditional trailing space with bash programmable completion
问题描述
我创建一个函数来提供,我使用一个命令完成可编程(从的 http://www.debian-administration.org/articles/317 )。 shell脚本用法如下:
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). The shell script usage is as follows:
script.sh command [command options]
在这里命令可以是'富'和'酒吧'和命令选项为'富'是'a_foo =价值和b_foo =价值和命令选项为巴是a_bar =价值和b_bar =价值。
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'.
下面是我使用的配置:
_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
这主要是工程,我想:
% script.sh f[TAB]
完成对:
% script.sh foo
(与根据需要一个空格)
(with a trailing space as desired)
然而,这样的:
% script.sh foo a[TAB]
完成对:
% script.sh foo a_foo
(也有一空格)
我想用一个'='来代替尾随空格。或者,我会愿意改变传递的值compgen是--a_foo = --b_foo =,在这种情况下,我可能只是删除尾随的空间。
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.
不幸的是,该命令是不是我的控制之下,所以我不能改变的命令行选项是格式--a_foo价值而不是--a_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".
推荐答案
首先,你需要=添加到COM prePLY:
First you need to add = to the 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;;
这篇关于使用bash的可编程完成条件尾随空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!