Makefile How to use variables defined in a config file

eye-catchOther techs
Sponsored links

It took me a while to clarify how to import variables from a config file.

We have makefile.env and define environment variables there.


This variable needs to be used in a makefile.

    @echo "HOST: " $(VM_HOST)
Sponsored links

Why is it necessary in the first place

Assume that another developer in the same project wants to connect to a VM to copy files by Make command for example.

The IP address could be different on each laptop.

I didn’t want to write the IP address to the makefile because the file is handled as a changed file by Git if another developer changes the setting in the makefile.

If we have a setting file that is ignored by .gitignore file, we don’t have to worry about an accidental commit.

Sponsored links


Add include

The first solution is to add include <path to the config file>.

include makefile.env
    @echo $(VM_HOST), ${VM_HOST}, $${VM_HOST}

    @echo "$(VM_HOST), ${VM_HOST}, $${VM_HOST}"

#,, ${VM_HOST}
    @echo '$(VM_HOST), ${VM_HOST}, $${VM_HOST}'

The environment variable can be accessed by $(VM_HOST) or ${VM_HOST}.

The environment is handled as a Make variable. Use a single dollar sign in this case.

Read the config file on the same line

The second solution is to read the file on the same line.

# , ,
    @. ./makefile.env && echo $(VM_HOST), ${VM_HOST}, $${VM_HOST}

# /bin/sh: 1: HDH_HOST: not found
# , ,, 
    @. ./makefile.env && echo "$(VM_HOST), ${VM_HOST}, $${VM_HOST}, $$(VM_HOST)"

# , , $${VM_HOST}, $(HDH_HOST)
    @. ./makefile.env && echo '$(VM_HOST), ${VM_HOST}, $${VM_HOST}, $$(VM_HOST)'

The environment variable can be accessed by $${VM_HOST}. Parentheses can’t be used for this.

The environment is handled as a Shell variable. Use two dollar sign in this case.

Be aware that if $${VM_HOST} is used in single quotes, it is handled as a string

Shell variable becomes empty if config file is read on another line

Don’t use the variable on a different line. It can’t be used in this case.

# HOST: 
    @. ./makefile.env && echo $${HDH_HOST}
    @echo "HOST: $${HDH_HOST}"


Copied title and URL