Bash – Writing a tab completion script for bash

autocompletebashshellshell-script

I made a shell script that reads input from user and kills a process. But in bash if the user presses Tab key then bash suggests some keyword or file names. My script however doesn't suggest anything.

How can I enable tab completion for my script ?

Best Answer

The easy way is to install bash-completion (or whatever else your distribution calls it), write a completion script, and put it in /etc/bash_completion.d. A basic completion script looks like this:

have cancel &&
_cancel()
{
    local cur

    COMPREPLY=()
    _get_comp_words_by_ref cur

    COMPREPLY=( $( compgen -W "$( lpstat | cut -d' ' -f1 )" -- "$cur" ) )
} &&
complete -F _cancel cancel

This is for the cancel command from cups. Read about COMPREPLY and compgen in the manual for bash, and adapt it to your needs.

Related Question