Shell自定义自动完成-不列出先前列出的参数



我已经编程自动完成到我的脚本,但当我输入TAB是显示以前填写的参数也。如何避免这种情况。

下面是我的代码:
_load_opt ()   
{                
  COMPREPLY=()   
  local cur=${COMP_WORDS[COMP_CWORD]}
  local prev=${COMP_WORDS[COMP_CWORD-1]}
  case "$prev" in
   "--create")
       COMPREPLY=( $( compgen -W "--name --type --size" -- $cur ) )  
       return 0 
       ;;
  "--delete")
        COMPREPLY=( $( compgen -W "--name" -- $cur ) )
        return 0 
       ;;
 esac
 if [[ ${cur} == -* ]]
 then
    COMPREPLY=($(compgen -W "--create --delete" -- $cur ) )
 return 0
fi
}
complete -F _load_opt ./run.sh `

我引用了这个脚本。当我运行

# ./run.sh --create --name file.txt --
--create  --delete  

由于最后一个默认的if语句,它是自动完成主参数。但是我想再次自动完成--type --size而不是--name

我试着用--create --name加一个case,但是我应该加所有的组合。这听起来不太对。

我怎样才能做到这一点?谢谢你的帮助。

要执行您想要的操作,您需要检查整个命令行,每次检查一个选项,如下所示(没有进行过多测试):(Edit:使用关联数组,为此您需要bash v4)

_load_opt () {
    # If we're at the beginning, only allow the verb options.
    if (( COMP_CWORD == 1 )); then
        COMPREPLY=($(compgen -W "--create --delete" -- "$2"));
    fi;
    if (( COMP_CWORD <= 1 )); then
        return;
    fi;
    # Otherwise, construct the list of allowed options based on the verb
    local -A flags;
    case ${COMP_WORDS[1]} in 
        --create)
            flags[--name]=ok;
            flags[--type]=ok;
            flags[--size]=ok
        ;;
        --delete)
            flags[--name]=ok
        ;;
        *)
            return 0
        ;;
    esac;
    # And scan the entire command line, even after the current point, for already
    # provided options, removing them from the list
    local word;
    for word in "${COMP_WORDS[@]:2}";
    do
        unset flags[$word];
    done;
    # Finally, complete either an option or an option value, depending on the
    # previous word (always the third argument to this function)
    # The first three lines in the case statement are just examples
    case $3 in
        --name) COMPREPLY=($(compgen -W "valid name list" -- "$2")) ;;
        --type) COMPREPLY=($(compgen -W "good bad ugly" -- "$2")) ;;
        --size) COMPREPLY=($(compgen -W "small medium large" -- "$2")) ;; 
        *) COMPREPLY=($(compgen -W "${!flags[*]}" -- "$2")) ;;
    esac
}

最新更新