【发布时间】:2021-07-05 03:19:40
【问题描述】:
您可以在这里找到相关问题:How to autocomplete a bash commandline with file paths?
上下文
我正在创建一个 shell 程序,它是一个命令行工具。我想为此工具创建自己的自动完成功能。
对于选项 --unit-test 和 -t,我想自动完成来自特定目录的文件路径,我可以运行 my_app --directory。
例如
运行:
user@computer:~$ my_app --install [TAB][TAB]
会做:
Public/ bin/ Desktop/
Documents/ Music/ Downloads/
user@computer:~$ my_app --install
(显示当前目录)
运行:
user@computer:~$ my_app --unit-tests [TAB][TAB]
会做:
folder/ folder2/ folder3/
.hidden_file file.extension file2.extension
user@computer:~$ my_app --unit-tests
(显示特定目录的建议而不用它完成)
my_app_autocomplete 文件
__my_app_autocomplete()
{
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
opts="--help -h --install -i --run -r --rebuild -rb --show-running-containers -ps --stop -s --remove -rm --logs -l --bash -b --sass -css --unit-tests -t"
containers="nginx php mysql mongo node"
sass="watch"
# By default, autocomplete with options
if [[ ${prev} == my_app ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
# By default, autocomplete with options
if [[ ${cur} == -* ]] ; then
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
return 0
fi
# For --install and -i options, autocomplete with folder
if [ ${prev} == --install ] || [ ${prev} == -i ] ; then
COMPREPLY=( $(compgen -d -- ${cur}) )
return 0
fi
# For --stop --remove --logs and --bash, autocomplete with containers
if [ ${prev} == --stop ] || [ ${prev} == -s ] || [ ${prev} == --remove ] || [ ${prev} == -rm ] || [ ${prev} == --logs ] || [ ${prev} == -l ] || [ ${prev} == --bash ] || [ ${prev} == -b ] ; then
COMPREPLY=( $(compgen -W "${containers}" -- ${cur}) )
return 0
fi
# For --sass and -css, complete with sass options
if [ ${prev} == --sass ] || [ ${prev} == -css ] ; then
COMPREPLY=( $(compgen -W "${sass}" -- ${cur}) )
return 0
fi
# For --unit-tests and -t, complete from a specific folder
if [ ${prev} == --unit-tests ] || [ ${prev} == -t ] ; then
COMPREPLY=( $(compgen -d -- ${cur}) )
return 0
fi
}
complete -o filenames -F __my_app_autocomplete my_app
问题
我找不到办法。你有什么想法吗?
调查
使用包含特定目录的变量
@D'Arcy Nader 建议
在my_app_autocomplete开头添加
_directory=/absolute/path/to/the/directory/
然后替换compgen命令中的变量
# For --unit-tests and -t, complete with relative to my_app folder paths
if [ ${prev} == --unit-tests ] || [ ${prev} == -t ] ; then
COMPREPLY=( $(compgen -d -- "${_directory}") )
return 0
fi
行为:
运行
user@computer:~$ my_app --unit-tests [TAB][TAB]
做
user@computer:~$ my_app --unit-tests /absolute/path/to/the/directory/
它添加了目录的路径。
运行
user@computer:~$ my_app --unit-tests /absolute/path/to/the/directory/file.ext[TAB][TAB]
做
user@computer:~$ my_app --unit-tests /absolute/path/to/the/directory/
它删除了file.ext 部分。
问题:
- 我不想在命令行中添加具体路径
- 它会删除我在特定目录之后添加的内容,而不是自动完成它。
【问题讨论】:
标签: linux bash autocomplete