首页 > 解决方案 > Makefile 检查文件夹和/或文件是否存在

问题描述

我有以下 Makefile:

build: clean
    ${GOPATH}/bin/dep ensure
    env GOOS=linux go build -o ./bin/status ./lib/status/main.go
    elm-app build

init:
    ${GOPATH}/bin/dep init -v

test:
    env GOOS=linux go test -v ./lib/status

strip:
    strip ./bin/status

clean:
    if [ -f ./bin/status ]; then
        rm -f ./bin/status
    fi

但我明白了

if [ -f ./bin/status ]; then
/bin/sh: 1: Syntax error: end of file unexpected
Makefile:16: recipe for target 'clean' failed
make: *** [clean] Error 2

我错过了什么?

非常感谢任何建议

标签: makefile

解决方案


makefile 的每一行都在一个单独的 shell 中运行。这意味着您的规则:

clean:
        if [ -f ./bin/status ]; then
            rm -f ./bin/status
        fi

实际运行以下命令:

/bin/sh -c "if [ -f ./bin/status ]; then"
/bin/sh -c "rm -f ./bin/status"
/bin/sh -c "fi"

您可以看到为什么会收到此消息。为确保将所有行发送到单个 shell,您需要使用反斜杠来继续这些行,如下所示:

clean:
        if [ -f ./bin/status ]; then \
            rm -f ./bin/status; \
        fi

请注意,这意味着您还需要在rm命令后使用分号,以便将其与结尾分开fi

现在你得到一个这样的 shell 调用:

/bin/sh -c "if [ -f ./bin/status ]; then \
        rm -f ./bin/status; \
    fi"

推荐阅读