如何在Makefile中实现自定义history命令查询功能?
问题描述
我一直用Makefile打包带有大量参数或标志的bash操作(我知道这并非它的原本用途),想在Makefile里实现这条命令:
history | tail -n 100 | cut -c 8- | sort | uniq
自己写了下面的Makefile但没法正常运行,求相关建议:
#* Setup .PHONY: $(shell sed -n -e '/^$$/ { n ; /^[^ .\#][^ ]*:/ { s/:.*$$// ; p ; } ; }' $(MAKEFILE_LIST)) .DEFAULT_GOAL := help help: ## list make commands @echo ${MAKEFILE_LIST} @awk 'BEGIN {FS = ":.*?## "} /^[a-zA-Z_-]+:.*?## / {printf "\033[36m%-30s\033[0m %s\n", $$1, $$2}' $(MAKEFILE_LIST) #* Commands get-history: ## custom history lookup command @history | tail -n 100 | cut -c 8- | sort | uniq HIS ?= ${history} test: ## test echo ${HIS}
解决方法
问题出在history命令的特性上:make执行命令时会启动非交互式非登录的bash shell,这种shell默认不会加载历史记录,也不会保存历史,所以直接调用history要么报错要么返回空结果。
要实现需求,直接读取bash的历史文件是最可靠的方式,默认路径是~/.bash_history,修改get-history目标如下:
get-history: ## custom history lookup command @tail -n 100 ~/.bash_history | sort | uniq
如果你的bash配置里通过HISTFILE环境变量修改过历史文件路径,可以改成读取该变量对应的文件,兼容性更好:
get-history: ## custom history lookup command @tail -n 100 ${HISTFILE:-~/.bash_history} | sort | uniq
另外你写的HIS ?= ${history}完全没用,${history}是make的变量,不是bash的命令,而且非交互式shell里history本身就没法正常输出,直接用历史文件才是正确思路。
内容的提问来源于stack exchange,提问作者willwrighteng
相关产品推荐
相关产品推荐

