gpt4 book ai didi

linux - Bash 中的自定义路径补全

转载 作者:IT王子 更新时间:2023-10-29 00:38:50 26 4
gpt4 key购买 nike

我想为我自己的文件系统编写一个 bash_completion 脚本。我有一个客户端程序,它向一些数据库发送查询。

例子:

my_prog --ls db_name:/foo/bar/

此命令写入 db_name:/foo/bar 文件夹中的标准输出文件列表。

我想为此启用自动完成功能。因此,当我按下 Tab 键时,它会显示选项列表。

my_prog --ls db_name:/foo/bar/<tab>

但在这种情况下,当我按下 Tab 键时,只有一个选项会替换当前输入的路径,所以我得到了这个:

$ my_prog --ls db_name:/foo/bar/<tab>
$ my_prog --ls file

但我希望将匹配项添加到输入路径的末尾。

这是我的完成函数:

__complete_path()
{
COMPREPLY=()

if [[ ${1} == "" ]]
then
COMPREPLY=( "/" )
compopt -o nospace
return
fi

base=${1##*/}
dir=${1%/*}

options="my_prog --ls ${db}:${dir}"
COMPREPLY=( $(compgen -W "${options}" -- ${base} ) )

compopt -o nospace
}

最佳答案

我在尝试类似的东西时发现了这个线程。 This stackexchange 帖子帮助我将下面的自动完成功能放在一起。它不像显示完整路径那样的“正常”自动完成,但您可能会发现它很有用。

_complete_func()
local cur prev opts
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"

if [ $COMP_CWORD -eq 1 ]; then
opts="some options for the program"
COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
elif [ $COMP_CWORD -ge 2 ]; then
local files=("${cur}"*)
COMPREPLY=( "${files[@]}")
fi
}
complete -o nospace -F complete_func command_to_autocomplete

关于linux - Bash 中的自定义路径补全,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39315586/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com