Script-specific autocomplete in shell

4

I create a lot of little scripts to help me in my every day life. I would like to provide auto-complete for them, specially that I intend to share them with people.

Now, I know I can create auto-complete functions that get sourced on login, but for the sake of elegance and portability, I seek to provide the autocomplete inside the script itself.

As I use zsh at home and bash on my VPS, I would like the script to be portable (or switch behaviors according to shell), but I would be content with already one solution, for either environment.

Xananax

Posted 2012-12-24T02:35:06.027

Reputation: 205

Answers

1

[F]or the sake of elegance and portability, I seek to provide the autocomplete inside the script itself.

You cannot do this from inside the shell script.

Traditionally, Bash completion for scripts and binaries is handled by entries in designated directories (e.g., /etc/bash_completion.d and /usr/share/bash-completion/completions for Bash).

However, all these do is call the built-in command complete with appropriate parameters. When calling your script for the first time, you can just make an entry either in one of those directories (requires root privileges) or in ~/.bashrc.

The basic syntax in the following:

# declare function to pass to `complete'
_myscript() 
{
    # declare variable `cur' (holds string to complete) as local
    local cur

    # initialize completion (abort on fail)
    _init_completion || return

    # if string to complete (`cur') begins with `-' (option)
    if [[ "$cur" == -* ]] ; then
        # complete to the following strings, if they start with `cur`
        COMPREPLY=( $( compgen -W '-a -b -c --foo --bar' -- "$cur" ) )
    else
        # otherwise, complete to elements in current directory that begin with `cur'
        _filedir -d
    fi

# if declaring the function was successful, use it when the command is `myscript'
} && complete -F _myscript myscript

For example, you could save the above to ~/.myscript_completion and append

source ~/.myscript_completion

to ~/.bashrc.

Dennis

Posted 2012-12-24T02:35:06.027

Reputation: 42 934

Not bad; I made it so when the script is called with --add-autocomplete, it runs the autocomplete function, so it can be sourced at start-up. – Xananax – 2012-12-25T14:52:42.327