小智 19
Make的并行性对shell脚本特别有用.假设您想获得一整套主机的"正常运行时间"(或基本上执行任何慢速操作).你可以在循环中做到这一点:
cat hosts | while read host; do echo "$host: $(ssh $host uptime)"; done
Run Code Online (Sandbox Code Playgroud)
这有效,但速度很慢.您可以通过生成子shell来并行化:
cat hosts | while read host; do (echo "$host: $(ssh $host uptime)")&; done
Run Code Online (Sandbox Code Playgroud)
但是现在你无法控制你产生的线程数,CTRL-C也不会干净地中断所有线程.
这是Make解决方案:将其保存到文件(例如showuptimes
)并标记为可执行文件:
#!/usr/bin/make -f
hosts:=$(shell cat)
all: ${hosts}
${hosts} %:
@echo "$@: `ssh $@ uptime`"
.PHONY: ${hosts} all
Run Code Online (Sandbox Code Playgroud)
现在运行cat hosts | ./showuptimes
将逐个打印正常运行时间.cat hosts | ./showuptimes -j
将并行运行它们.调用者可以直接控制并行化程度(-j
),也可以通过系统负载(-l
)间接指定它.