列出特定路径的目录作为 bash 脚本的自动完成选项?
List directories at a specific path as autocomplete options for a bash script?
我的 .bash_profile 中有一个名为 repos 的 bash 函数,为此我想要添加列出特定目录内容的自动完成功能。我正在尝试使用 complete
命令来实现这一点。
简而言之,我尝试过的是:
创建了一个名为 repos_complete.bash 的文件,其中包含以下代码。此后我 运行 source repos_complete.bash
以确保它适用于 repos 脚本。
repos_complete.bash
中的代码:
complete -A directory repos
目前的结果:如果我输入repos
,然后按tab,它会列出当前目录的内容。然而,我想要的是它列出另一个目录的内容,例如~/source/repos/
.
我尝试将 repos_complete.bash 的内容替换为以下内容:
complete -C ls ~/source/repos repos
但是现在输入 repos
和 tab 时,我收到一条错误消息:
Cannot access 'repos': no such file or directory
在我看来,-C
(随后接受命令)将整行解释为命令,包括最后一个“repos
”,而不是仅应用第一个部分 (ls ~/source/repos
) 作为函数 repos 的命令,这就是我想要实现的目标。
这里有关于正确传递 ls <some path>
命令的正确方法的提示吗?
注意:我应该指出,这是 运行ning 在 git bash shell 下 windows 的上下文中] 10,以防万一。
我认为您需要填充 COMPREPLY
数组。我认为这可行:
_repos()
{
local cur;
local base=~/source/repos/
_get_comp_words_by_ref cur;
cur="$base$cur"
_filedir
COMPREPLY=("${COMPREPLY[@]#$base}")
} && complete -o nospace -F _repos repos
如果你想使用-C
选项,你可以使用下面这个方法。 (请注意,我没有对包含特殊字符的文件名进行评估。)
_repos()
{
( cd ~/source/repos; printf "%s\n" ""* )
} && complete -o nospace -C _repos repos
complete -C
没有像您预期的那样工作的原因是 -C
应该采用本身带有三个参数的命令。来自 Bash manual:
When the function or command is invoked, the first argument () is the name of the command whose arguments are being completed, the second argument () is the word being completed, and the third argument () is the word preceding the word being completed on the current command line.
因此,如果您想使用 complete
的 -C
形式,您似乎需要一个自定义命令。
我的 .bash_profile 中有一个名为 repos 的 bash 函数,为此我想要添加列出特定目录内容的自动完成功能。我正在尝试使用 complete
命令来实现这一点。
简而言之,我尝试过的是:
创建了一个名为 repos_complete.bash 的文件,其中包含以下代码。此后我 运行 source repos_complete.bash
以确保它适用于 repos 脚本。
repos_complete.bash
中的代码:
complete -A directory repos
目前的结果:如果我输入repos
,然后按tab,它会列出当前目录的内容。然而,我想要的是它列出另一个目录的内容,例如~/source/repos/
.
我尝试将 repos_complete.bash 的内容替换为以下内容:
complete -C ls ~/source/repos repos
但是现在输入 repos
和 tab 时,我收到一条错误消息:
Cannot access 'repos': no such file or directory
在我看来,-C
(随后接受命令)将整行解释为命令,包括最后一个“repos
”,而不是仅应用第一个部分 (ls ~/source/repos
) 作为函数 repos 的命令,这就是我想要实现的目标。
这里有关于正确传递 ls <some path>
命令的正确方法的提示吗?
注意:我应该指出,这是 运行ning 在 git bash shell 下 windows 的上下文中] 10,以防万一。
我认为您需要填充 COMPREPLY
数组。我认为这可行:
_repos()
{
local cur;
local base=~/source/repos/
_get_comp_words_by_ref cur;
cur="$base$cur"
_filedir
COMPREPLY=("${COMPREPLY[@]#$base}")
} && complete -o nospace -F _repos repos
如果你想使用-C
选项,你可以使用下面这个方法。 (请注意,我没有对包含特殊字符的文件名进行评估。)
_repos()
{
( cd ~/source/repos; printf "%s\n" ""* )
} && complete -o nospace -C _repos repos
complete -C
没有像您预期的那样工作的原因是 -C
应该采用本身带有三个参数的命令。来自 Bash manual:
When the function or command is invoked, the first argument () is the name of the command whose arguments are being completed, the second argument () is the word being completed, and the third argument () is the word preceding the word being completed on the current command line.
因此,如果您想使用 complete
的 -C
形式,您似乎需要一个自定义命令。