Tab autocompletion for Bash scripts.
- Make script.sh globally visible (add it's directory to $PATH).
- Add
source /full/path/to/autocomplete.shto~/.bashrc. - Relogin.
| Naming file |
| _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 |