Ryan Ryan - 2 months ago 13
Bash Question

Is it possible to add an alias in bash that allows tab completion?

I have lots of log files in a deeper directory like so:

/my/deep/path/to/log/files/
foo-2016-10-10.log
foo-2016-10-11.log
bar-2016-10-10.log
bar-2016-10-11.log


Many times a day I find myself tailing different logs like so:

tail -fn 100 /my/deep/path/to/log/files/foo-2016-10-10.log


Is it possible to alias everything but the final file? And allow tab completion to get me the rest of the way?

For example, I'd love to type
tl
(short for tail log) and the specific log file I'm looking for like so:

$ tl foo
[HIT TAB KEY]
$ tl foo-2016-10-1
[HIT 1 and TAB KEY]
$ tl foo-2016-10-11.log


Is this possible in bash? How can I accomplish this?

Answer

Pretty much a clone of Charles Duffy's answer (with the only difference that he uses globs and I'm using compgen — which is probably the way completions are (badly) designed to be written):

_tl_COMPDIR=/my/deep/path/to/log/files/
_comp_tl() {
   local IFS=$'\n'
   COMPREPLY=( $(compgen -f -- "$_tl_COMPDIR$2") )
   COMPREPLY=( "${COMPREPLY[@]#"$_tl_COMPDIR"}" )
}

tl() (
   cd -- "$_tl_COMPDIR" && tail -fn 100 "$@"
)

complete -o nospace -o filenames -F _comp_tl tl
Comments