mardi 6 avril 2021

Makefile: how to use a command which randomly generates a file or leaves it unchanged

I have a command which sometimes updates a target file, sometimes it leaves it unchanged, but I cannot tell which one of those will happen. I would like to create a dependency which should run ONLY if the first file is updated. I could not do this. Here is a simple Makefile that reproduces this problem:

all: file2.txt

file1.txt:
    @if [ ! -f file1.txt -o $(shell bash -c "expr \$$RANDOM \% 2") = 1 ]; \
    then \
        echo "update" >> file1.txt; \
        echo "file1.txt overwritten"; \
    else \
        echo "file1.txt is unchanged"; \
    fi

.PHONY: file1.txt

file2.txt: file1.txt
    cp file1.txt file2.txt

The test in the rule for file1.txt will generate file1.txt if it does not exists or if a random number modulo 2 is 1. I would like to see cp file1.txt file2.txt executed if and only if file1.txt is overwritten.




Aucun commentaire:

Enregistrer un commentaire