Run script only on modified file using Makefile


Run script only on modified file using Makefile



I have few txt files in a directory. I want to run a shell script only on the files which have been modified. How can I achieve this through Makefile?
Have written the following part but it builds all the txt files in the directory. Would be great to get some pointers on this.


txt


Makefile


txt


FILENAME:= $(wildcard dir/txts/*/*.txt)

.PHONY: build-txt
build-txt: $(FILENAME)
sh build-txts.sh $^





Define modified -- are they newer than a particular target, or just modified since the last time this makefile was run in that directory?
– HardcoreHenry
2 days ago





@HardcoreHenry modified since the last time makefile ran
– dejavu
2 days ago




1 Answer
1



I'm guessing you want something like this:


files := $(wildcard dir/txts/*/*.txt)
dummies := $(addprefix .mod_,$files)

all:$(dummies)

$(dummies): .mod_% : %
sh build-txts.sh $^
touch $@



For any new text file, it will run the script, and create a .mod counterpart. For any non-new text file, it will check if the timestamp is newer than the .mod files timestamp. If it is, it runs the script, and then touches the .mod (making the .mod newer than the text). For any text file that has not been modified since the last make, the .mod file will be newer and the script will not run. Notice that the .mod files are NOT PHONY targets. They are dummy files who exist solely to mark when the text file was last modified. You can stick them in a dummy directory for easy cleaning as well.



If you need something where you don't want to rebuild the text files by default on a fresh checkout, or your script criteria isn't based on timestamps, you would need something a bit more tricky:


files := $(wildcard dir/txts/*/*.txt)
md5s:= $(addprefix .md5_,$files)

all:$(md5s)

.PHONY:$(md5s)
$(md5s):
( [ -e $@ ] && md5sum -c $@ ) ||
( sh build-txts.sh $@ && md5sum $(@:.md5_=) > $@ )



Here, you run the rule for all text files regardless, and you use bash to determine if the file is out of date. If the text file does not exist, or the md5sum is not correct, it runs the script, then updates the md5sum. Because the rules are phony, they always run for all the .md5sum files regardless of whether they already exist.



Using this method, you could submit the .md5 files to your repository, and it would only run the script on those files whose md5 sum changed after checkout.





The first parameter of addprefix is the prefix, not the list of words to prefix.
– Renaud Pacalet
2 days ago


addprefix






By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

Comments

Popular posts from this blog

paramiko-expect timeout is happening after executing the command

Opening a url is failing in Swift

Visual Studio 2017 errors on standard headers