如何在Makefile中输入父目录? [英] How to enter a parent directory in Makefile?
问题描述
我有以下Makefile
(GNU Make 3.81):
I've got the following Makefile
(GNU Make 3.81):
CWD:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
all:
pwd
cd "$(CWD)/.."
pwd
cd ".."
pwd
以下是输出:
$ make
pwd
/Users/kenorb/temp/foo
cd "/Users/kenorb/temp/foo/.."
pwd
/Users/kenorb/temp/foo
cd ".."
pwd
/Users/kenorb/temp/foo
似乎cd
通过..
进入父目录没有任何作用.
It seems that cd
'ing to parent directory via ..
doesn't take any effect.
如何相对于Makefile
文件将当前工作目录更改为父目录?
How do I change the current working directory to a parent directory relatively to Makefile
file?
推荐答案
此问题与以下事实有关:规则配方的每一行都在专用的shell实例(即新进程)中执行.因此,在一行中运行cd
不会对另一行中的命令产生任何影响,因为这些命令是由不同的进程执行的.
This issue has to do with the fact that each line of a rule's recipe is executed in a dedicated shell instance (i.e.: a new process). So, running cd
in one line, won't have any effect for a command in another line, because these commands are executed by different processes.
您可以使用 .ONESHELL
(GNU Make 3.82或更高版本)可在单个相同的shell实例中运行所有配方行:
You can either use .ONESHELL
(GNU Make 3.82 or later) to run all the recipe's lines in a single and the same shell instance:
CWD:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
.ONESHELL:
all:
pwd
cd "$(CWD)/.."
pwd
cd ".."
pwd
或仅将所有命令放在一行中:
or just keep all the commands in a single line:
CWD:=$(shell dirname $(realpath $(lastword $(MAKEFILE_LIST))))
all:
pwd; cd "$(CWD)/.."; pwd; cd ".."; pwd
更改工作目录仅在该食谱内部生效.
The change of the working directory takes effect only inside that recipe.
请注意,无法为调用make
的shell更改makefile中的当前工作目录,因为这是一个process'属性,并且正在运行的make
实例将执行cd
是另一个(子)过程.因此,它只会更改该子进程的工作目录.
Note that changing the current working directory inside the makefile for the shell that invoked make
is not possible, since that's a process' property, and the running make
instance that will execute cd
is another (sub)process. Therefore, it will only change the working directory of that subprocess.
这是您不能通过执行脚本而没有 sourcing 来更改Shell工作目录的相同原因:因为脚本在新的Shell实例(即子进程)中运行.
That is the same reason you cannot change the working directory of a shell by executing a script without sourcing it: because the script runs in a new shell instance (i.e.: a subprocess).
这篇关于如何在Makefile中输入父目录?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!