2012-12-08 3 views
23

필자는 필요한 경우 데이터베이스를 삭제하는 것을 포함하여 데이터베이스를 다시 만들 목적으로 다음을 Makefile에 가지고 있습니다. 작동하지 않습니다.Makefile 작업에서 쉘 변수를 사용하려면 어떻게해야합니까?

.PHONY: rebuilddb 
    exists=$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM pg_database WHERE datname='the_db'") 
    if [ $(exists) -eq 1 ]; then 
     dropdb the_db 
    fi 
    createdb -E UTF8 the_db 

실행이 오류가 발생합니다

$ make rebuilddb 
exists= 
if [ -eq 1 ]; then 
/bin/sh: -c: line 1: syntax error: unexpected end of file 
make: *** [rebuilddb_postgres] Error 2 

왜 잘못인가? 내가 말할 수있는 한 유효한 배쉬처럼 보인다? Makefile에서이 작업을 수행 할 때 특별히 고려해야 할 사항이 있습니까? 내가 작업 버전에 도착 대답 사용

:

UPDATE

.PHONY: rebuilddb 
    exists=$$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM pg_database WHERE datname='the_db'"); \ 
    if [ "$$exists" == "1" ]; then \ 
     dropdb the_db; \ 
    fi; 
    createdb -E UTF8 the_db 

답변

38

는 적어도 두 가지 고려 사항이 있습니다. $()은 Make 변수를 참조합니다. 명령 대체를 수행하려면 $을 탈출해야합니다. 또한 쉘 명령은 모두 한 행에 있어야합니다. 시도 :

한편
exists=$$(psql postgres --tuples-only --no-align --command "SELECT 1 FROM \ 
    pg_database WHERE datname='the_db'"); \ 
    if [ "$$exists" -eq 1 ]; then \ 
     dropdb the_db; \ 
    fi; \ 
    createdb -E UTF8 the_db 

, 그냥 항상 데이터베이스를 제거하려고 허용하는 간단한 것처럼 보인다 실패 : 모든 페이지의 "에 대한

있습니다
rebuilddb: 
    -dropdb the_db # Leading - instructs make to not abort on error 
    createdb -E UTF8 the_db 
+3

몇 뉘앙스 한 줄 "은 논의할만한 가치가 있습니다 : (전통적으로 그리고 이식 가능한) ** 동일한 쉘 **에 의해 실행되기를 원하는 모든 것은 하나의 논리적 _make_ 라인에 있어야합니다. 그러므로'존재 = ... '와'if ... fi'는 세미콜론과 백 슬래시가있는 단일 명령 행으로 만들어야하지만'createdb ...'는 제조법에서 별도의 두 번째 명령으로 행복하게 남을 수 있습니다. –

+1

독자들에게 :'VAR = "foo"\'문장의 끝에'\'을 넣었는지 확인하십시오. – redolent

+1

"all in one line"은 https : //www.gnu.org/software/make/manual/html_node/One-Shell.html#One-Shell – sdive

관련 문제