问题
I am having trouble generating a package with a md5sum of the contained files using Makefiles.
I do have found an workaround, but I am not satisfied with it.
This is a example of how my makefile works, it can be used to reproduce my problem with file1
, and my workaround with file2
.
VERSION:=1
DIR:=tmp
file: #rule to build the file with current version tag
touch $(DIR)/file-$(VERSION)
$(DIR)/file1.tar:file #rule that fails to create the md5 file
cd $(DIR)
md5sum -b \
file-$(VERSION) \
>> file-$(VERSION).md5
tar -cf $@ \
file-$(VERSION) \
file-$(VERSION).md5
cd -
$(DIR)/file2.tar:file #workaround that fails to create the md5 file
md5sum -b \
$(DIR)/file-$(VERSION) \
>> $(DIR)/file-$(VERSION).md5
tar -cf $@ -C $(DIR) \
file-$(VERSION) \
file-$(VERSION).md5
file1: $(DIR) $(DIR)/file1.tar
file2: $(DIR) $(DIR)/file2.tar
$(DIR):
mkdir -p $(DIR)
Running file1
, the build fails and I get the following output:
:~/tmp$ make file1
mkdir -p tmp
touch tmp/file-1
cd tmp
md5sum -b \
file-1 \
>> file-1.md5
md5sum: file-1: No such file or directory
Makefile:8: recipe for target 'tmp/file1.tar' failed
make: *** [tmp/file1.tar] Error 1
Running file2
, the file is built successfully:
:~/tmp$ make file2
touch tmp/file-1
md5sum -b \
tmp/file-1 \
>> tmp/file-1.md5
tar -cf tmp/file2.tar -C tmp \
file-1 \
file-1.md5
My question is, why md5sum
tool fails to find the file in the same dir as it is running after calling cd dir
when it is used as a Makefile
instruction? Or, what I am missing?
回答1:
Each line in a recipe is executed by a separate shell invocation. So your cd $(DIR)
line is executed by a shell and has no effect on the next line (md5sum...
) that gets executed by another shell. In your case a simple solution consists in chaining all commands such that they are considered as a single line by make and executed by the same shell:
target: prerequisites
cd here; \
do that; \
...
or:
target: prerequisites
cd here && \
do that && \
...
来源:https://stackoverflow.com/questions/49493821/md5sum-fails-to-find-file-after-changing-dir-in-a-makefile-instruction