Last Updated: February 25, 2016
·
2.977K
· spanneberg

Use bash auto completion support to increase your productivity

As I started lookin' into Gradle I was wondering if it would be possible to autocomplete on tasks as it works e.g. for git subcommands (and I really got used to that!). It really saves you a lot of typing and increases your flow in the shell.

As it turned out, the bash (which I am using luckily) has support to enable you to write your own scripts for bash autocompletion and that the forementioned git autocompletion is nothing else than such a script.

To get an idea of how things work, the first place to look at is

/etc/bash_completion

This file is doing all the basic setup stuff and is sourced in your .bashrc file or in /etc/bash.bashrc. It also automatically sources all files in /etc/bash_completion.d/, to enable eays extensions for new commands.

To come back to my goal (getting task completion for Gradle), it seems that I was not the only one lookin' for something like that and the appropriate script to put into /etc/bash_completion.d can be found in the Gradle Cookbook:

#!/bin/bash

_gradle_complete()
{
local cur tasks

COMPREPLY=()
cur=${COMP_WORDS[COMP_CWORD]}
tasks='clean compile dists javadoc jar test war'
cur=`echo $cur | sed 's/\\\\//g'`
COMPREPLY=($(compgen -W "${tasks}" ${cur} | sed 's/\\\\//g') )
}

complete -F _gradle_complete -o filenames gradle

And that is all there is! When you open your next shell, the new completion will be active and you will get completion for all the tasks you've put into the tasks variable in the script. Just put your most common tasks in there. It's no dynamic completion based on the build file, but still this is very helpful and helps increasing your flow on the commandline.

And if you miss completion on some other command, just take a look into the existing scripts, learn and adopt!

2 Responses
Add your response

you can also have this a bit more dynamic: https://gist.github.com/ligi/882552790dd6d5646912

over 1 year ago ·

Great hint! Thx!

over 1 year ago ·