Search code examples
bashtab-completionbash-completion

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


Some commands have many -x (x can be any English letter) options and it's some times difficult to remember all of their meanings. I can use bash's compgen -W '-a -b -c' to show possible options and I'm wondering if it's possible to also show some help message. Like this:

bash# foo -<TAB><TAB>
-a: This is option a    -b: This is option b
-C: This is option c
bash#

Solution

  • I ever did something similar to map some of curl's single char options (like -x) to GNU style --long-options.

    This is 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 -
    

    Not exactly what you asked but you can update it for your own purpose.

    (I'm not sure if bash can handle whitespaces in the completion result but at least you can use _ or -. :-)