How to customise bash completion to pick only a custom set of commands?

105 views Asked by At

Is there a way to control bash completion to pick only a few commands instead of everything in the path, aliases and functions? We can set a default handler for empty command line but when the first letter is typed, bash goes for completing it with PATH, aliases and functions. Is there a way to customise the completion for the command search?

Example:

$m[tab] mycmd1 mycmd2 mycmd3

instead of the commands that match in PATH, aliases and functions.

1

There are 1 answers

1
AKS On

The following should remove the "word" from the completion list. Completion functions just return a bash array and you can manipulate it to contain whatever you like:

_b() {
        local word=${COMP_WORDS[COMP_CWORD]}
        COMPREPLY=($(compgen -f -- "${word}"))
        if [[ "$word" ]]; then
                local  w
                local  i=0
                local  n=${#COMPREPLY[*]}
                while [[ $i -lt $n ]]
                do
                        w=${COMPREPLY[$i]}
                        COMPREPLY[$i]="${w:${#word}}"
                        let i++
                done
        fi
}

I don't see any way to get a completion to work for all commands but I suppose you could always do something like this if you really need to:

for c in /bin/* /usr/bin/* ~/bin/*
do
        complete -F _b $(basename $c)
done

Now, you can tweak the above code sections to get what you are trying to find (i.e. only some commands). Hint.