Is it possible to display some help message when showing candidates for autocomplete?

Some commands have many options -x( xcan be any English letter), and several times it is difficult to remember all their meanings. I can use bash compgen -W '-a -b -c'to show possible options, and I wonder if it is possible to show some kind of help message as well. Like this:

bash# foo -<TAB><TAB>
-a: This is option a    -b: This is option b
-C: This is option c
bash#
+2
source share
2 answers

I have ever done something similar to display some of the curlsingle char parameters (e.g. -x) in GNU --long-options style .

Here's how it works:

[STEP 101] # cat curl
function _compgen_curl()
{
    local cmd=$1 cur=$2 pre=$3
    local -a options=( \
                       '' --connect-timeout \
                       -k --insecure \
                       -m --max-time \
                       -o --output \
                       -O --remote-name \
                       -u --user \
                       -U --proxy-user
                       -x --proxy \
                       -y --speed-time \
                       -Y --speed-limit \
                     )
    local -a options2=()
    local i short long

    for ((i = 0; i < ${#options[@]}; i += 2)); do
        short=${options[i]}
        long=${options[i+1]}
        if [[ -z $short || -z $long ]]; then
            options2+=( $short$long )
        else
            options2+=( $short,$long )
        fi
    done

    if [[ $cur == - ]]; then
        COMPREPLY=( $( compgen -W "${options2[*]}" -- "$cur" ) )
    elif [[ $cur == --* ]]; then
        COMPREPLY=( $( compgen -W "${options[*]}" -- "$cur" ) )
    fi
}

complete -F _compgen_curl -o bashdefault -o default curl

 

[STEP 102] # . ./curl
[STEP 103] # curl -<TAB><TAB>
--connect-timeout  -o,--output        -u,--user          -y,--speed-time
-k,--insecure      -O,--remote-name   -x,--proxy
-m,--max-time      -U,--proxy-user    -Y,--speed-limit
[STEP 103] # curl -

, , .

( , bash , _ -.: -)

+2

, .

, : , , , , . , .

:

complete -o nospace -F _default_completion my_command

:

_custom_completion(){
    local cur;
    _get_comp_words_by_ref cur;
    _default_completion
    if [ ${#COMPREPLY[@]} == 1 ]; then return; fi
    local _compreply=()
    local reply_entry
    local description
    for reply_entry in ${COMPREPLY[@]}; do
        description=$(generate_description_from_option "$reply_entry")
        description=$(printf "%${COLUMNS}s" "$reply_entry : $description" )
        _compreply+=$description
    done
    COMPREPLY=(${_compreply[@]})
} && complete -o nospace -F _custom_completion my_command

bash . , generate_description_from_option .

+1

Source: https://habr.com/ru/post/1684106/


All Articles