Enable bash Completion for Makefile Targets
24 Jun 2018 Linux tips shell makefileThe bash-completion package does not handle command make
,
while we can extend the completion support for make
by adding bash configurations with keyword complete
.
Solution
In ~/.bashrc
or ~/.bash_profile
file, add the following:
complete -W "\`if [ -f Makefile ]; then grep -oE '^[a-zA-Z0-9_-]+:([^=]|$)' Makefile | sed 's/[^a-zA-Z0-9_-]*$//'; elif [ -f makefile ]; then grep -oE '^[a-zA-Z0-9_-]+:([^=]|$)' makefile | sed 's/[^a-zA-Z0-9_-]*$//'; fi \`" make
This complete
entry would add a completion rule for command make
.
The option -W
is followed by a word list as completion contents.
The word list is generated by a series command:
first check whether regular file Makefile
or makefile
exist at current path,
then using grep
and regular expression to extract targets in makefile,
finally sed
to word list.
Also note that
bash’s if-elif conditional statements use semi-colon to separate condition, execution, condition, execution …
And finally ends with fi
.
With the edition to bash configuration described above,
now we are able to press tab to complete targets for make
or press tab twice to see candidates.
Limitations
Makefile or makefile must be at the same path where you type the command,
which means the solution cannot work with make
’s option -C
.
Because it simply searches the specific file (./Makefile
or ./makefile
),
the targets in other makefile included by the primary makefile would not appear in the completion.
Credits
- bash completion of makefile target - Thank Cibin Joseph for the .bashrc solution.