Skip to content

Instantly share code, notes, and snippets.

@tetafro
Last active September 8, 2016 10:45
Show Gist options
  • Save tetafro/8e6eda38f982ccb9c3f7ebc60ae460c0 to your computer and use it in GitHub Desktop.
Save tetafro/8e6eda38f982ccb9c3f7ebc60ae460c0 to your computer and use it in GitHub Desktop.
Tab autocompletion for Bash scripts

Description

Tab autocompletion for Bash scripts.

Setup

  1. Make script.sh globally visible (add it's directory to $PATH).
  2. Add source /full/path/to/autocomplete.sh to ~/.bashrc.
  3. Relogin.
_autocomplete() {
_commands='help list'
_opts='all even odd'
local cur prev
COMPREPLY=()
cur="${COMP_WORDS[COMP_CWORD]}"
prev="${COMP_WORDS[COMP_CWORD-1]}"
if [[ $prev == 'script.sh' ]]; then
COMPREPLY=( $(compgen -W "${_commands}" -- ${cur}) )
elif [[ $prev == 'list' ]]; then
COMPREPLY=( $(compgen -W "${_opts}" -- ${cur}) )
fi
return 0
}
complete -F _autocomplete script.sh
#!/bin/bash
command=$1
option=$2
case $command-$option in
help-)
echo 'Here is your help'
;;
help-*)
echo 'Error'
;;
list-all)
echo '1, 2, 3, 4'
;;
list-even)
echo '2, 4'
;;
list-odd)
echo '1, 3'
;;
list-*)
echo 'Error'
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment