Fight for the Internet 1!

Sunday, September 20, 2009

Tab Complete with Bash Functions

About two years ago I had trouble figuring out how to program bash shell script functions to use tab-completion options. Here is what I learned, hopefully it will help someone out there, someday.

How to programming TAB completion into bash functions, programs and other such things.

Minimum Requirements
Here are the minimum requirements for BASH tab completion.
Code:
# 'local' can only be used within a function, exclude it if not using a function
COMPREPLY=()
local cur="${COMP_WORDS[COMP_CWORD]}"
local opts="--whatever --tabbing --options --you --want"
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))

Lastly, you need one more line after this somewhere in the file, usually after your function:

complete -F "function_name" -o "default" "function_name"
# Replace function_name with your function
Example
A simple example with the current code:

Code:

function sd
{
# 'local' can only be used within a function, exclude it if not using a function
COMPREPLY=()
local cur="${COMP_WORDS[COMP_CWORD]}"
local opts="--whatever --tab --options --you --want to have!"
COMPREPLY=($(compgen -W "${opts}" -- ${cur}))
if [[ ! $* =~ \n ]]; then # Check command been submitted, no more tab-completing
  echo "Command submitted"
  ... # more bash code, dealing with submitted command arguments
fi 

}
complete -F "sd" -o "default" "sd"
# complete -F "sd" -o "nospace" "sd" ## Use this if you do not want a space after the completed word
Slighty Advanced
You can manipulation the string input however you want, just make sure you clear COMPREPLY, and grab the current command prompt info, and append them using compgen.

2 comments:

  1. Used your note! But wanted to make something clearer:
    in
    complete -F "your-completing-function" -o "options" "the-function-that-needs-autocomplete"

    "your-completeing-function" needs to contain those first code segment lines. this function can then be used for any function that needs autocomplete from these words.

    Thanks!

    ReplyDelete