来自命令的 Makefile 变量值

Makefile variable value from command

我有一个 Docker 容器 运行,我想用 make kill 杀死它。

这是我的 Makefile:

kill:
    CONTAINER=$(docker ps -a -q  --filter ancestor=container-name); \
    docker kill $$CONTAINER

它给出错误:

CONTAINER=; \
docker kill $CONTAINER
"docker kill" requires at least 1 argument.
See 'docker kill --help'.

变量CONTAINER似乎是空的。 然而 运行 在 shell:

$(docker ps -a -q  --filter ancestor=container-name)

Returns 容器 id,实际上它打印:

c1cddc4d19a0: command not found

我假设您没有定义一个名为 docker ps -a -q --filter ancestor=container-name 的 make 变量,而是想 运行 作为一个程序并获取它的输出。

如果是这样,您需要在此处转义 $,就像您对变量所做的那样:

kill:
        CONTAINER=$$(docker ps -a -q  --filter ancestor=container-name); \
        docker kill $$CONTAINER

否则 make 认为 $(docker ps -a -q --filter ancestor=container-name) 是对不存在变量的引用,将替换为空字符串。