Search code examples
randommakefiletarget

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 that 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.


Solution

  • By adding the .PHONY setting you are specifically telling make that no matter what that target is always considered out of date, so you're directly contradicting what you want to do.

    You can use another method to handle this via a "force target", like this:

    FORCE: ;
    file1.txt: FORCE
             ...
    

    and remove the .PHONY setting.