uni farm

Makefile使い方メモ

Makefile使い方メモ

Makefileを使うと長いscriptを保存して、簡単なコマンドで使えるようになる dockerやgolangのプロジェクトでよく見かける (もともとMakefileとはなんなのかよくわからないまま書いている)

基本の書き方

以下のような規則で書く必要がある

target: dependencies
    system command(s)
  • target: makefileコマンドで呼び出すときの名前
  • dependencies: targetが実行される前に呼び出されるtarget
  • system command(s): 実行されるスクリプト

コマンド行はtabでインデントしないと動かないので注意

例)

# comment
shell-mkdir:
  mkdir test/
shell-ls:shell-mkdir
  ls

makefilefileのあるディレクトリにて makefile shell-lsを実行すると、testディレクトリが作られた後にlsコマンドが実行される

make shell-ls
mkdir -p test/
ls 
test        Makefile

変数を扱う

シェルみたいに定義できる

SSH_KEY=`cat ~/.ssh/id_rsa
install: 
	docker build --build-arg SSH_KEY="$(SSH_KEY)" .
	docker build -f Dockerfile.test --build-arg SSH_KEY="$(SSH_KEY)" 

引数を扱う

?=を使うことでデフォルトの値を代入できる

SSH_KEY=`cat ~/.ssh/id_rsa`
DOCKER_REPO?=test
DOCKER_TAG?=1.0

docker-image:
	docker build --build-arg SSH_KEY="$(SSH_KEY)" -t "$(DOCKER_REPO)":"$(DOCKER_TAG)" .

引数指定なし

make docker-image
...

docker images
REPOSITORY          TAG                 IMAGE ID            CREATED              SIZE
test                1.0                 234526e3b4d5        About a minute ago   42MB

引数指定あり

make docker-image DOCKER_REPO=test_arg DOCKER_TAG=1.0_arg
...

docker images
REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE
test_arg            1.0_arg             234526e3b4d5        7 minutes ago       42MB

参考

2023, Built with Gatsby. This site uses Google Analytics.