gpt4 book ai didi

bash - bash 脚本中的自动完成

转载 作者:行者123 更新时间:2023-12-05 08:14:57 29 4
gpt4 key购买 nike

我正在尝试在 bash 脚本中自动完成文件夹名称。如果我输入完整的文件夹名称,一切正常,但我不知道如何自动完成名称。有什么想法吗?

repo() {
cd ~/Desktop/_REPOS/$1
}

我尝试阅读 this SO post的想法,但很快就迷失了方向,因为我对 bash 还是很陌生。

目标(上面的 repo 函数包含在我的 bashrc 中):

>ls ~/Desktop/_REPOS/
folder1
hellofolder
stackstuff

>repo sta[TAB] fills in as: repo stackstuff

最佳答案

实际上你可以从geirha's answer 借用相当多的代码:

# this is a custom function that provides matches for the bash autocompletion
_repo_complete() {
local file
# iterate all files in a directory that start with our search string
for file in ~/Desktop/_REPOS/"$2"*; do
# If the glob doesn't match, we'll get the glob itself, so make sure
# we have an existing file. This check also skips entries
# that are not a directory
[[ -d $file ]] || continue

# add the file without the ~/Desktop/_REPOS/ prefix to the list of
# autocomplete suggestions
COMPREPLY+=( $(basename "$file") )
done
}

# this line registers our custom autocompletion function to be invoked
# when completing arguments to the repo command
complete -F _repo_complete repo

for 循环遍历目录中以作为 _repo_complete 函数第二个参数的字符串开头的所有文件(这是要自动完成的字符串)。

将代码添加到您的 .bashrc 中,它应该可以工作!

关于bash - bash 脚本中的自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39624071/

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