realpath 不适用于新创建的文件

时间:2021-01-21 23:21:56

标签: makefile gnu-make

test :
    touch test
    echo $(realpath test)
    echo $(shell realpath test)
    rm test

当我运行 make 时,$(realpath test) 返回空字符串,而 $(shell realpath test) 返回预期结果。为什么是这样?我试过使用 .ONESHELL 但它没有什么区别。

1 个答案:

答案 0 :(得分:1)

首先,shell realpath 和 GNU make realpath 函数是不同的。即使文件不存在,Shell realpath 也会返回一个路径:

/home/me$ rm -f blahblah
/home/me$ realpath blahblah
/home/me/blahblah

但是,如果文件不存在,GNU make 的 realpath 将返回空字符串。

那么,为什么文件不存在?因为 make 会在运行配方的任何行之前扩展配方的所有行

这意味着像 $(realpath ...)$(shell ...) 这样的 make 函数首先被扩展,在配方的第一行 (touch test) 运行之前......展开 test 文件不存在。

一般来说,您永远不想在配方中使用 make 的 $(shell ...) 函数,并且不能使用 make 构造与发生在配方中的操作“交互”。您应该为此使用 shell 函数:

test :
        touch test;
        echo $$(realpath test)
        rm test
相关问题