定义自动完成子命令的最简单方法

问题描述 投票:0回答:1

我有一个 CLI 程序,其中有一些嵌套子命令,例如

program task
program task start
program task stop
program config
program config set
program config unset

我想为其实现一个非常基本的 bash 自动完成功能。我不一定想为其定义一个shell函数,但希望简单地使用单词列表,比如

complete -W "task config" -- "program"

但我似乎无法以这种方式定义嵌套完成单词列表,就像

complete -W "start stop" -- "program task"
complete -W "set unset" -- "program config"

有没有一种简单的方法来实现此类命令的自动完成?

bash autocomplete
1个回答
0
投票

这是我在评论中提到的 _get_comp_words_by_ref 函数的示例。

# "program" completion

# This file should either be copied in your system-defined place where other
# such completion scripts reside, such as /usr/share/bash-completion/completions
# or /etc/bash_completion.d (check which one is called by your .bashrc file).
#
# Alternatively, simply 'source' it in your .bashrc file.


function _program () {

  _get_comp_words_by_ref -c CURRENT_WORD -p PREVIOUS_WORD -w WORDS_ARRAY -i CURRENT_WORD_INDEX


  if   test "$CURRENT_WORD_INDEX" -eq 2     &&   # dealing with a second-level subcommand
       test "${WORDS_ARRAY[0]}" = "program"
  then if   test "$PREVIOUS_WORD" = "task"
       then COMPREPLY=( $( compgen -W "start stop" -- $CURRENT_WORD ) )
       elif test "$PREVIOUS_WORD" = "config"
       then COMPREPLY=( $( compgen -W "set unset" -- $CURRENT_WORD ) )
       fi
  elif test "$CURRENT_WORD_INDEX" -eq 1 && test "$PREVIOUS_WORD" = "program"
  then COMPREPLY=( $( compgen -W "task config" -- $CURRENT_WORD ) )
  fi

}

complete -F _program program

获取此文件并尝试输入program co[TAB]、program config u[TAB]等。

© www.soinside.com 2019 - 2024. All rights reserved.