Skip to content

Instantly share code, notes, and snippets.

@bmcculley
Last active October 24, 2018 06:16
Show Gist options
  • Save bmcculley/0c3c9355d2e8d1080c92d11fe3479e6b to your computer and use it in GitHub Desktop.
Save bmcculley/0c3c9355d2e8d1080c92d11fe3479e6b to your computer and use it in GitHub Desktop.
Bash autocomplete example

Using demo

  1. Download the zip file
  2. Navigate to the download directory and unzip unzip <filename>.zip
  3. Source the completion file (source ./completion)
  4. Give psa execute rights (chmod +x psa)
  5. Add psa to PATH (export PATH=$PATH:`pwd`)
  6. psa <tab> <tab>

Oneliner

wget -q https://gist.github.com/bmcculley/0c3c9355d2e8d1080c92d11fe3479e6b/download -O temp.zip; unzip -qq temp.zip -d example; rm temp.zip; cd example/`ls example`; source ./completion; chmod +x psa; export PATH=$PATH:`pwd`
#!/usr/bin/env bash
read -r -d '' TOP_CHOICES <<- EOM
help
list
status
start
stop
kill
configure
purge
flush
restart
bounce
EOM
read -r -d '' TYPE_CHOICES <<- EOM
web
app
prcs
EOM
_build_response()
{
local suggested_results
local CHOICES=$1
local CWORD=$2
local suggestions=($(compgen -W "${CHOICES}" "${CWORD}"))
if [ "${#suggestions[@]}" == "1" ]; then
COMPREPLY=("${suggestions[0]}")
else
for i in "${!suggestions[@]}"; do
suggestions[$i]="$(printf '%s' "${suggestions[$i]}")"
done
COMPREPLY=("${suggestions[@]}")
fi
}
_completions()
{
local cur prev
cur=${COMP_WORDS[COMP_CWORD]}
prev=${COMP_WORDS[COMP_CWORD-1]}
case ${COMP_CWORD} in
1)
_build_response "${TOP_CHOICES}" "${cur}"
;;
2)
case ${prev} in
status|start|stop|kill|restart|bounce)
_build_response "${TYPE_CHOICES}" "${cur}"
;;
esac
;;
*)
;;
esac
}
complete -F _completions psa
#!/usr/bin/env bash
if [ -z "$1" ]; then
echo "No command to execute."
exit 2
else
echo "Excuting command $@."
exit 0
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment