有一个小需求,将一个目录包括子目录中的coffee文件批量转换到另一个指定的目录中,同时保挂子目录的结构。改了一个类似的Makefile。发一下备忘:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 | coffeeBaseDir=coffee/ coffeeDir=$(abspath $(coffeeBaseDir)) jsBaseDir=js/ jsDir=$(abspath $(jsBaseDir)) jsFile=$(shell find $(coffeeBaseDir) - type f -name *.coffee | sed 's@^$(coffeeBaseDir)@$(jsDir)/@g' | sed 's@\.coffee$$@\.js@g' ) jsDeploy: $(jsFile) $(jsDir)/%.js: $(coffeeDir)/%.coffee @ mkdir -p ` sed 's@/[^/]\+$$@/@g' <<< '$@' ` coffee -bp $< > $@ test : @ echo $(jsFile) clean: @ rm js -fr @ echo 'clean success!' |
测试结果:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | > find coffee - type f coffee /abc .coffee /3 .coffee coffee /abc .coffee /1 .coffee coffee /abc .coffee /2 .coffee coffee /p1/3 .coffee coffee /p1/1 .coffee coffee /p1/2 .coffee coffee /p2/3 .coffee coffee /p2/1 .coffee coffee /p2/2 .coffee coffee /p3/3 .coffee coffee /p3/1 .coffee coffee /p3/2 .coffee > find js - type f js /abc .coffee /2 .js js /abc .coffee /1 .js js /abc .coffee /3 .js js /p1/2 .js js /p1/1 .js js /p1/3 .js js /p2/2 .js js /p2/1 .js js /p2/3 .js js /p3/2 .js js /p3/1 .js js /p3/3 .js |
工作中用makefile执行打包、压缩、转换等功能,一个需求涉及到多层相对路径嵌套,于是想到将相对路径转换为绝对路径。百度谷歌数遍,找到一曲径通幽的方法。
PUBLICDIR = $(shell cd ../public; pwd)
*2012年11月16日更新
经依云大大提点,又上网搜索了一下Makefile相关函数。Makefile自带有两个函数可以得到绝对路径。
1. realpath 函数获取文件名序列中存在的文件和目录的真实路径,会判断文件和目录是否存在,如果不存在,则返回空。
2. abspath 函数获取文件名序列中存在的文件和目录的真实路径,函数不会检查文件或者目录是否存在。
示例:
PUBLICDIR = $(abspath ../public; pwd)
经本人测试,realpath abspath 能跨过软链接,获取文件的真实路径。
例如:
ln -s /usr/local/www /www
Makefile:
WWWDIR = $(abspath /www)
test:
echo $(WWWDIR) #output /usr/local/www
make test #output /usr/local/www