bash completion of makefile target

前端 未结 6 1992
小蘑菇
小蘑菇 2021-01-31 01:59

Suppose I have a simple makefile like:

hello:
   echo \"hello world\"

bye:
   echo \"bye bye\"

Then in bash I want something like:

6条回答
  •  伪装坚强ぢ
    2021-01-31 02:45

    Add this in your ~/.bash_profile file or ~/.bashrc file

    complete -W "\`grep -oE '^[a-zA-Z0-9_.-]+:([^=]|$)' ?akefile | sed 's/[^a-zA-Z0-9_.-]*$//'\`" make
    

    This searches for a target in your Makefile titled 'Makefile' or 'makefile' (note the capital ? wildcard in ?akefile) using grep, and pipes it over to the complete command in bash which is used to specify how arguments are autocompleted. The -W flag denotes that the input to the complete command will be a wordlist which is accomplished by passing the results of grep through sed which arranges it into the desirable wordlist format.

    Caveats and gotchas:

    1. Your make file is named 'GNUMakefile' or anything else other than 'Makefile' or 'makefile'. If you frequently encounter such titles consider changing the regular expression ?akefile accordingly.

    2. Forgetting to source your ~/.bash_profile or ~/.bashrc file after making the changes. I add this seemingly trivial detail since, to the uninitiated it is unfamiliar. For any change to your bash files to take effect, source them using the command

      source ~/.bashrc
      

      or

      source ~/.bash_profile
      

    PS. You also now have the added ability to display the possible make targets by pressing [Tab] twice just like in bash completion. Just make sure you add a space after the command make before typing [Tab] twice.

提交回复
热议问题