带有目录和固定集的自定义 bash 完成

dai*_*isy 4 bash autocomplete

我正在尝试设置 bash 完成,但有两个问题

  1. 对于参数一,我需要完成目录
  2. 对于参数二,一个用于完成的固定数组,我只是不知道如何让 bash 进行选择,之前我总是使用 perl 脚本进行复杂的选择。
_some_func()
{
    case $COMP_CWORD in
    1)
        # default completion ? how
        ;;
    2)
        COMPREPLY=( "go" "unbind" )
        # I should be using a program to echo "go" and "unbind",
        # and let bash decide which one to complete , right ? 
        # that's the only two possible parameters here
        ;;
    esac
}

complete -F _some_func some_func
Run Code Online (Sandbox Code Playgroud)

Gil*_*il' 5

这是一种方法:设置dirnames为默认完成,并为第二个参数生成自定义完成。

_some_func () {
  case $COMP_CWORD in
    1) :;; # let the default take over
    2) COMPREPLY=($(compgen -W "go unbind" "${COMP_WORDS[$COMP_CWORD]}"));;
    *) COMPREPLY=("");;
  esac
}
complete -F _some_func -d some_func
Run Code Online (Sandbox Code Playgroud)

您也可以调用compgen -dwhen $COMP_CWORDis 1,但这在 bash 中效果不佳,因为您需要在 的输出中转义空格compgen,并且您无法区分分隔两个结果的换行符和包含在完成中的换行符(罕见,但可能)。