How to use $variable in conditional sentences?

Hello all

I am doing a Makefile but I can't return the value of $var to use it in conditional sentences:

#!/bin/sh

GO=$(shell) go
GOPATH=$(GO) env GOPATH

make:
    @$(GOPATH)
    @if [ ! -d "$(GOPATH)/bin" ]; then mkdir -p "$(GOPATH)/bin" ; fi

When I type "make", @$GOPATH returns /home/icvallejo/go so it's ok, but after, I don't know how to use it (I can't do it) with 'if' condition, make returns this:

if [ ! -d " go env GOPATH/bin" ] ; then mkdir -p " go env GOPATH/bin" ; fi

Can you help me please?

I think you mix up two different things: shell scripts and makefiles.

Makefiles (more precisely: the make -utility) work rule-based, so you don't need explicit conditionals - everything is a conditional anyway.

make works like that: you define so-called "dependencies" between files: i.e. you have three object files where each depends on a single source file. Whenever one of the source file changes the corresponding object file has to be generated anew. This is done by executing the code in the rule-definition. For every dependency you can create a rule, but usually you create rules for groups of dependencies: whenever ".c" (the source) changes, the corresponding ".obj" (the object) has to be generated and the rule for this is to call the compiler to compile exactly the one source-file. For this there are "make-variables" like "$@", "$<", etc., which are filled with the name(s) of the files involved in the rule. See the man-page of make for details.

You can also create cascades of these rules: you base .obj -files on .c -files and you base executables on the .obj -files. So, when a source file changes, the corresponding object is generated and in turn this leads to the executable being generated too (by calling the linker to link all the objects to the executable.

You might want to read this little introduction i once wrote.

I hope this helps.

bakunin

1 Like

Thank you @bakunin, now I understand the difference but it's funny because if I type gmake it works... lol

I have no idea what you're trying to do. What is "go"? What are you actually trying to accomplish?

If this "go" command loads variables or changes the current directory, it won't work, makefiles do not work that way, they are not shell scripts. The paths and variables should be set up before you run make, not after.

I'm sorry, I didn't explain myself correctly. go is to execute go (golang) commands.

But now it works typing gmake ...

It occurs to me your makefile is a little overcomplicated.

instead of if [ ! -d ... ] ; then mkdir -p ; fi just do mkdir -p $(GOPATH)/bin that being what the -p flag is for.

Or add these lines to the end:

$(GOPATH)/bin:
        mkdir -p $(GOPATH)/bin

No need to dump the logic into shell when makefile can handle it natively.

Of course, then you should add it to your make: line so make knows to 'build' that first: make:$(GOPATH)/bin

1 Like