Mihai Danila Mihai Danila - 3 months ago 7
Bash Question

Using the Bash autocompletion of another command

When I create a command that wraps an existing command with some sugar, I'd like the new command to support the autocompletion of the original command. Is there a way to tell Bash to reuse the autocompletion script of another command?

Silly example:

cat > ~/ls-on-steroids.sh <<EOF
echo "Here are some goodies!"
ls "$@"
EOF
chmod +x ~/ls-on-steroids.sh


Now, how do I configure my new script such that when I type:

~/ls-on-steroids.sh <TAB><TAB>


I'd like the same behavior as with:

ls <TAB><TAB>


Preferably in a portable, repeatable manner, without having to manually track down the location of
ls
's autocomplete script.

Answer

You have to configure it manually, but it's relatively simple to copy completions from an existing command. First, run complete -p ls to see what, if any, command was defined for ls. If nothing comes up, ls doesn't use any special completions. You are probably expecting to see something like the following as the output, though

complete -o default -F _longopt ls

which says that the function _ls is called to generate completions for the command ls, and if the doesn't generate any results, use the bash default completion. You can apply the same function to ls_on_steroids by simply running

complete -o default -F _longopt ls_on_steroids

(i.e., replace ls with ls_on_steroids as the final argument in the command printed by complete -p).