Eugen Konkov
Eugen Konkov

Reputation: 25113

Why variable is not expanded in makefile?

In my Makefile I have rule:

dbrestoretable:
    line=$$(zcat ${APP_ROOT}/db/${TABLE}.dump.sql.gz | head -n 1)
    zcat ${APP_ROOT}/db/${TABLE}.dump.sql.gz | \
        psql -h ${DB_HOST} -p ${DB_PORT} -U ${DB_USER} ${DB_NAME} -c \
            "BEGIN;COPY ${TABLE}($$line) FROM STDIN WITH( FORMAT CSV, HEADER );COMMIT;"  ||:

When I execute it I get error:

line=$(zcat /home/mmkeeper/maitre_d_backend/monkeyman/db/i18n.dump.sql.gz | head -n 1)
zcat /home/mmkeeper/maitre_d_backend/monkeyman/db/i18n.dump.sql.gz | \
        psql -h 127.0.0.1 -p 5433 -U tucha tucha -c \
            "BEGIN;COPY i18n($line) FROM STDIN WITH( FORMAT CSV, HEADER );COMMIT;"  ||:
ERROR:  syntax error at or near ")"
LINE 1: BEGIN;COPY i18n() FROM STDIN WITH( FORMAT CSV, HEADER );COMM...
                        ^

Why $$line is not expanded?

Upvotes: 0

Views: 44

Answers (1)

ErikMD
ErikMD

Reputation: 14723

This is because each line of a Makefile rule is run in a separated shell, and in particular the variable line defined in the first line of your rule won't be kept for the second line of your rule.

Try this instead:

dbrestoretable:
    line=$$(zcat ${APP_ROOT}/db/${TABLE}.dump.sql.gz | head -n 1) ; \
    zcat # etc.

or if need be:

dbrestoretable:
    export line=$$(zcat ${APP_ROOT}/db/${TABLE}.dump.sql.gz | head -n 1) ; \
    zcat # etc.

FYI the relevant documentation of this "feature" is described in this page of the doc of GNU make.

Upvotes: 1

Related Questions