0%

Tab Completion for Bash and Zsh

Suppose you have files structured as follows:

1
2
3
4
.
└── manifests
├── abc123.manifest
└── xyz456.manifest

You want to define a bash command mytool that can achieve the follows:

1
2
3
4
5
$ mytool <TAB>
abc123 xyz456

$ mytool 12<TAB>
abc123

zsh

If you are an oh-my-zsh user, this can be accomplished by adding the following lines into ~/.zshrc:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
# The actual tool that passes the argument to a python script
mytool()
{
python ~/mytool.py $@
}

# The completion function that helps user quickly input the arguments
_mytool() {
# zsh completion variable
local state

# separate arguments into different groups
_arguments \
'1: :->exp'\
'*: :->others'

# Take the basename of files in $FOLDER and ends with $FILEEXT
FOLDER="$PWD/manifests"
FILEEXT=".manifest"

local files=()
for f in $FOLDER/*$FILEEXT; do
files+=("${${f/$FILEEXT/}/$FOLDER\/}");
done

# tab completion only for the first argument
case $state in
(exp) _arguments '1:profiles:( $files )' ;;
(*) compadd "$@" ''
esac
}
compdef _mytool mytool

bash

tbd.