【问题标题】:bash completion: description text when pressing TAB (sort of heredoc for autocompletion)bash 完成:按 TAB 时的描述文本(用于自动完成的 heredoc)
【发布时间】:2020-08-03 16:12:27
【问题描述】:

我为我的脚本创建了一个漂亮的自动完成功能。

但有一件事:当参数留给用户决定时(例如,第一个参数是新项目的名称),我想显示一行描述预期的内容。

For example:
$> script [TAB][TAB]
<name of project>
$> script my_new_project

.

当然,我想过这个:

if [ $COMP_CWORD -eq 1 ]; then
        local IFS=$'\n'
        COMPREPLY+=($(compgen -W "<name of project>"))

问题是我得到了这个:

$> script [TAB][TAB]
$> script <name of project>

也就是说,当我按 TAB 时,我定义的一个文本会自动添加到命令行中。

.

我也试过这个:

local IFS=$':'
COMPREPLY+=($(compgen -W "Help: <domain name associated with the project>"))

但是结果是乱码,还是在命令行中加了字:

$> script [TAB][TAB]
<domain name associated with the project> Help:
$> script <domain name associated with the project>

.

请问,您知道如果有一种heredoc 用于自动完成,它只会显示帮助文本,但不会添加到命令行?

谢谢!

【问题讨论】:

  • 您可能会发现this approach 很有用。我还没试过。但我也需要你要求的同样效果。
  • 哇,有时需要耐心^^谢谢您的评论,我会尽快看看
  • 我已经用 heredoc 示例更新了答案。

标签: bash autocomplete completion


【解决方案1】:

您可以随时在完成脚本中的任何需要使用printf。这是我会做的:

if [ $COMP_CWORD -eq 1 ]; then
   printf "\n *** Enter a project name: %s" "${COMP_LINE[@]}"
fi

打印COMP_LINE 数组对于第一个参数并不是特别有用。如果您有更多参数并希望向用户显示他们迄今为止输入的内容,打印COMP_LINE 可能是这样做的方法。

此外,您可能希望向用户建议现有的项目名称。在这种情况下:

if [ $COMP_CWORD -eq 1 ]; then
   printf "\n *** Enter a project name: %s" "${COMP_LINE[@]}"
   list_of_project_names=("project1" "theotherproject" "testproject")
   COMPREPLY=($(compgen -W "${list_of_project_names[@]}" -- "$2"))
fi

请注意,在完成脚本中,$2 是正在完成的当前单词,$3 是前一个单词,$1 是当前命令行中的第一个单词。

对于更长的描述,您可以使用'heredoc':

if [ $COMP_CWORD -eq 1 ]; then
  cat<<EOF
# leave a blank line for formatting

*** You can select a project from suggestions or enter a
*** name for your new project:
EOF
  # Use _printf_ for printing the "${COMP_LINE[@]}" because
  # the _heredoc_ adds a newline to the end.
  printf ">>> %s" "${COMP_LINE[@]}"
  list_of_project_names=("project1" "theotherproject" "testproject")
  COMPREPLY=($(compgen -W "${list_of_project_names[@]}" -- "$2"))
fi

您还可以使用read 命令和-e 选项,如此处建议的https://stackoverflow.com/a/4819945/6474744

对于更复杂的行为,您可能会发现这个有趣的https://brbsix.github.io/2015/11/29/accessing-tab-completion-programmatically-in-bash/

干杯

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-09
    • 2015-02-02
    • 2012-11-14
    • 1970-01-01
    • 1970-01-01
    • 2010-12-22
    • 2015-09-13
    相关资源
    最近更新 更多