我正在学习 bash 补全。我只能列出当前目录的内容。这是我的代码:
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="push pull"
OUTPUT=" $(ls) "
case "${prev}" in
push)
COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
return 0
;;
--in)
COMPREPLY=( $(compgen -W "$OUTPUT" -- ${cur}) )
return 0
;;
esac
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
return 0
}
complete -F _foo foo
它的输出是:
$ foo push --in[TAB]
file1.txt file2.txt foo ;; content of pwd
但是当我这样做时:
$ foo push --in ~[TAB]
它不工作。 所以我想知道如何在不同的目录中完成 bash(不仅仅是在 pwd 中)?谢谢。
最佳答案
您可以使用-f
来匹配文件名:
#!/bin/bash
_foo() {
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="push pull"
case "${prev}" in
push)
COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
return 0
;;
--in)
COMPREPLY=( $(compgen -f ${cur}) )
return 0
;;
esac
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
return 0
}
complete -F _foo foo
但是,它似乎不适用于单独的 ~
但 $ foo push --in ~/[TAB]
以及所有其他目录
此解决方案不会包含斜杠来在目录中查找文件: $ foo push --in/etc[TAB]
将给出 foo push --in/etc
而不是 foo push --in/etc/
以下帖子使用默认模式解决了该问题:
Getting compgen to include slashes on directories when looking for files
default
Use Readline’s default filename completion if the compspec generates no matches.
所以你可以使用:
#!/bin/bash
_foo()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="push pull"
OUTPUT=" $(ls) "
case "${prev}" in
push)
COMPREPLY=( $(compgen -W "--in --out" -- ${cur}) )
return 0
;;
--in)
COMPREPLY=()
return 0
;;
--port)
COMPREPLY=("")
return 0
;;
esac
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
return 0
}
complete -o default -F _foo foo
或者当您需要喜欢这篇文章时设置为默认模式:https://unix.stackexchange.com/a/149398/146783
关于bash - 如何在其他目录中扩展 bash 补全?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38285872/