在查找文件时让 compgen 在目录中包含斜杠 [英] Getting compgen to include slashes on directories when looking for files
问题描述
我想从我的自定义完成中获得以下行为
I'd like to get the following behavior from my custom completion
给定
$ mkdir foo
$ touch foo faz/bar faz/baz
我想要这个
$ foo -u <tab><tab> =>
foo faz/
$ foo -u fa<tab><tab> =>
foo -u faz/
$ foo -u faz/<tab><tab> =>
bar baz
我假设 compgen -ff
会输出 foo faz/
,但它输出的 foo faz
对我没有多大帮助.
I assumed that compgen -f f
would output foo faz/
, but it outputs foo faz
which doesn't help me much.
我是否需要对输出进行后处理,或者是否有一些神奇的选项组合来compgen 起作用?
Do I need to post-process the output or is there some magic combination of options to compgen that work?
推荐答案
我遇到了同样的问题.这是我正在使用的解决方法:
I ran into the same problem. Here's the workaround I'm using:
- 使用
-o default
注册完成函数,例如,complete -o default -F _my_completion
. - 当你想完成一个文件名时,只需设置
COMPREPLY=()
并让 Readline 接管(这就是-o default
所做的).
- Register the completion function with
-o default
, e.g.,complete -o default -F _my_completion
. - When you want to complete a filename, just set
COMPREPLY=()
and let Readline take over (that's what the-o default
does).
这有一个潜在的问题——您可能正在使用 COMPREPLY=()
在不合适的地方拒绝完成,现在这将不再起作用.在 Bash 4.0 及更高版本中,您可以使用 compopt
解决此问题,如下所示:
There's a potential problem with this -- you might be using COMPREPLY=()
to deny completion where it's not appropriate, and now that won't work anymore. In Bash 4.0 and above, you can work around this using compopt
as follows:
- 在完成函数的顶部,始终运行
compopt +o default
.当COMPREPLY
为空时,这会禁用 Readline 文件名补全. - 当你想完成一个文件名时,使用
compopt -o default;COMPREPLY=()
.换言之,仅在需要时启用 Readline 文件名补全.
- At the top of your completion function, always run
compopt +o default
. This disables Readline filename completion whenCOMPREPLY
is empty. - When you want to complete a filename, use
compopt -o default; COMPREPLY=()
. In other words, enable Readline filename completion only when you need it.
我还没有想出 4.0 之前的 Bash 的完整解决方法,但我有一些对我来说足够好用的方法.如果有人真的关心,我可以描述这一点,但希望这些较旧的 Bash 版本无论如何很快就会被淘汰.
I haven't figured out a full workaround for pre-4.0 Bash, but I have something that works well enough for me. I can describe this if anyone really cares, but hopefully these older Bash versions will soon fall out of common use anyway.
这篇关于在查找文件时让 compgen 在目录中包含斜杠的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!