2014
Mar
28

Makefile 在 Linux 环境下,通常是用来撰写编译 c 语言的指令,例如我们会使用 「make」的指令来编译各种软体。

Makefile 用途

我通常会用 Makefile 来写一些自动化的指令,例如说压缩 CSS/JS 档案,我平常就直接使用 gmake compress 来将 JS 合并成一支档案,并且自动透过 yuicompressor 压缩。

compress js
  1. compress:
  2. if [ -f "all.js" ]; then rm all.js ; fi
  3. touch all.js
  4. cat xx1.js >> all.js
  5. cat xx2.js >> all.js
  6. cat all.js | java -jar /usr/local/lib/yuicompressor-2.4.6.jar --charset utf8 --type js -o all.js

另外一种用途是用来备份

backup
  1. Y=`date +%Y`
  2. M=`date +%m`
  3. D=`date +%d`
  4. H=`date +%H`
  5. date=$Y"-"$M"-"$D"-"$H
  6. backup:
  7. tar -zcf ~/$date-data1.tar.gz /xxx/xx1
  8. tar -zcf ~/$date-data2.tar.gz /xxx/xx2
  9. scp ~/*.gz 192.168.x.x:~/backup
  10. rm ~/*.gz

if 判断式

判断档案是否存在

file is exist.
  1. ifneq ("$(wildcard /usr/local/xxx/xx.Makefile)","")
  2. FILE_EXISTS = 1
  3. include /usr/local/xxx/xx.Makefile
  4. else
  5. FILE_EXISTS = 0
  6. endif

变数预设值设定

如果设定预设值,例如我想要预设值 M_name = Marry ,但是当指令有带参数时, M_name 又可以等於传入的参数。

变数设定
  1. ifneq (, $(name))
  2. M_name=$(name)
  3. else
  4. M_name=Marry
  5. endif
  6. test:
  7. echo $(M_name)
  8. //gmake test name=John // output John
  9. //gmake test // output Marry

字串取代

replace
  1. input=abc
  2. str=$(shell echo $(input) | sed 's/c/_/')
  3. test:
  4. echo $(str)

for 回圈

forloop
  1. test_for:
  2. length=$${#files[@]}; \
  3. for(( j=0; j<$$length; j++ )); \
  4. do \
  5. parse=`echo "$${files[$$j]}" | sed -e 's/.less/.css/g'` ; \
  6. sudo ls \
  7. done

string to array

array
  1. run:
  2. str="$(dir)"; \
  3. files=($${str// / }); \
  4. length=$${#files[@]}; \
  5. echo $$length; \

取得当前目录

Example
  1. SELF_DIR := $(dir $(lastword $(MAKEFILE_LIST)))
  2. include $(SELF_DIR)Makefile.os

区分作业系统 os

Example
  1. UNAME_S := $(shell uname -s)
  2. ifeq ($(UNAME_S),Linux)
  3. os=Linux
  4. endif
  5. ifeq ($(UNAME_S),Mac)
  6. os=Mac
  7. endif

回應 (Leave a comment)