Question

I want to write my own auto completion. But the parameters should be accesible without facing dashes

Here is my current working example

# /etc/bash_completion.d/radio
_radio()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="--foo --bar --baz"


    if [[ ${cur} == -* ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _radio radio

What do I have to change to get it working without dashes?

Was it helpful?

Solution

If I understood you correctly, you want your command to work something like:

$ radio <tab><tab>
bar  baz  foo

If so, just get rid of the dashes.

Here is your script modified, think it should work:

# /etc/bash_completion.d/radio
_radio()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="foo bar baz"


    COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
    return 0
}
complete -F _radio radio

OTHER TIPS

@Vivek is mostly right but if you remove the if entirely then you'll be able to keep on tab completing for ever:

$ radio bar foo baz<tab>
bar  baz  foo

Instead you should change the if to look for only the 2nd word:

_radio()
{
    local cur prev opts
    COMPREPLY=()
    cur="${COMP_WORDS[COMP_CWORD]}"
    prev="${COMP_WORDS[COMP_CWORD-1]}"
    opts="foo bar baz"

    # only tab complete second word in command string
    if [[ ${#COMP_WORDS[@]}  == 2 ]] ; then
        COMPREPLY=( $(compgen -W "${opts}" -- ${cur}) )
        return 0
    fi
}
complete -F _radio radio
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top