Any interesting uses of Makefiles to share?

后端 未结 7 1689
北恋
北恋 2020-12-23 18:14

\"make\" is not only useful for building your programming project, but it seems to be under-used in other areas.

For example, many shell scripts can be rewritten as

7条回答
  •  不思量自难忘°
    2020-12-23 18:42

    Make's parallelism is particularly handy for shell scripting. Say you want to get the 'uptime' of a whole set of hosts (or basically perform any slow operation). You could do it in a loop:

    cat hosts | while read host; do echo "$host: $(ssh $host uptime)"; done
    

    This works, but is slow. You can parallelise this by spawning subshells:

    cat hosts | while read host; do (echo "$host: $(ssh $host uptime)")&; done
    

    But now you have no control over how many threads you spawn, and CTRL-C won't cleanly interrupt all threads.

    Here is the Make solution: save this to a file (eg. showuptimes) and mark as executable:

    #!/usr/bin/make -f
    
    hosts:=$(shell cat)
    all: ${hosts}
    
    ${hosts} %:
            @echo "$@: `ssh $@ uptime`"
    
    .PHONY: ${hosts} all
    

    Now running cat hosts | ./showuptimes will print the uptimes one by one. cat hosts | ./showuptimes -j will run them all in parallel. The caller has direct control over the degree of parallelisation (-j), or can specify it indirectly by system load (-l).

提交回复
热议问题