khinester
khinester

Reputation: 3530

Makefile check if folder and/or file exists

I have the following 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

but I get

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

what am i missing?

any advice is much appreciated

Upvotes: 5

Views: 15983

Answers (1)

MadScientist
MadScientist

Reputation: 101081

Each line of a makefile is run in a separate shell. This means your rule here:

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

actually runs the following commands:

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

You can see why you get this message. To ensure that all lines are send into a single shell you need to use backslashes to continue the lines like this:

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

Note this means you also need a semicolon after the rm command so separate it from the ending fi.

Now you get a shell invocation like this:

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

Upvotes: 14

Related Questions