Take the 2-minute tour ×
Super User is a question and answer site for computer enthusiasts and power users. It's 100% free, no registration required.

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.

share|improve this question

1 Answer 1

up vote 1 down vote accepted

[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.

share|improve this answer
    
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 Dec 25 '12 at 14:52

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.