[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.,
/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
The basic syntax in the following:
# declare function to pass to `complete'
# declare variable `cur' (holds string to complete) as local
# 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" ) )
# otherwise, complete to elements in current directory that begin with `cur'
# 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