gpt4 book ai didi

狂欢 : read + completion

转载 作者:行者123 更新时间:2023-11-29 09:29:49 24 4
gpt4 key购买 nike

我是 bash 的新手,我正在尝试编写一个 bash 脚本来保存用户的输入(一些标签),以帮助这个用户我想允许仅根据我个人的预定义标签列表完成而不是关于常见的TAB文件补全(文件夹中的文件名)。

predefinedtags=(one two three four five)
echo "enter tags (separate multiple values by space)"
read -e tags
echo $tags

我希望在 read 输入期间,用户可以按 TAB 来完成带有预定义标签列表的单词。我认为这是一个常见的问题和方法,但我没有找到一个好的方法来做到这一点。我发现一些帖子对我来说有点太复杂了,他们似乎解释说这不是一个简单的问题。我什至不知道这是否可能。

Changing tab-completion for read builtin in bash

bash and readline: tab completion in a user input loop?

你有什么想法吗?或者可能有一种完全不同的方法来做到这一点?感谢您的帮助。

最佳答案

在第二部分,有一个简单的版本。

试试这个经过测试的版本:

#!/bin/bash --

reade () {
tmpdir=$(date "+/tmp/%Y%m%d%H%M%S$$")
mkdir "${tmpdir}"
for ptag in "${predefinedtags[@]}" ; do
touch "${tmpdir}"/"${ptag}"
done
readetags=$(cd "${tmpdir}" || printf "internal error" ; read -re usertags ; printf "%s" "${usertags}")
rm -rf "${tmpdir}" 2>/dev/null >/dev/null
eval "${1}"=\"\$\{readetags\}\"
}
predefinedtags=(one two three four five)
printf "enter tags (separate multiple values by space)\n"
reade tags
printf "%s\n" "${tags}"

这可能看起来很奇怪,但很有趣! (并使用 shellcheck 检查)

它定义了一个新的read 函数,该函数创建一个具有唯一名称的临时目录,并为predefinedtags 中的每个元素创建一个空文件。它将当前目录更改为新的临时目录并运行 read -e

TAB 键将按预期工作。

最后将用户输入的标签全部赋值给tags

注意不要将带有空格或特殊字符(如 '"(等))的标签插入到预定义标签中。

----

第二部分

您可能想要定义一个已经包含空文件(预定义标签)的配置目录,而不是创建和删除临时目录。

在下面的脚本中将 /path/to/configuration 替换为 configuration 目录的真实路径:

#!/bin/bash --

printf "enter tags (separate multiple values by space)\n"
tags=$(cd /path/to/configuration || printf "internal error" ; read -re usertags ; printf "%s" "${usertags}")
printf "%s\n" "${tags}"

测试(写TAB键的地方):

$ ls configuration/
five four one three two

$ ./script.sh
enter tags (separate multiple values by space)
TAB
five four one three two
five ten
five ten

$ touch configuration/cat
$ ls configuration/
cat five four one three two

$ ./script.sh
enter tags (separate multiple values by space)
TAB
cat five four one three two
cat hello
cat hello

关于狂欢 : read + completion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36521152/

24 4 0