Makefile rule depending on the change in the number / headers of files instead of changing the contents of files

I use a makefile to automate the creation of some documents. I have several documents in a directory, and one of my makefile rules will generate an index page for these files. The list of the files themselves is loaded on the fly using list := $(shell ls documents/*.txt), so I don’t need to manually edit the makefile every time I add, delete or rename a document. Naturally, I want the index generation rule to be triggered when the number / headers of files in the document directory change, but I don’t know how to set up prerequisites for working this way.

I could use .PHONYor something similar to make index generation work all the time, but I would prefer not to waste these loops. I tried piping lsto a file list.txtand used this as a prerequisite for my index generation rule, but for this you will need to either edit it list.txtmanually (trying to avoid it) or auto-generate it in a makefile (this changes the creation time, so I cannot use it list.txtin the prerequisite because it runs the rule every time).

+3
source share
3 answers

, ... ? , , documents.

NUMBER=$(shell ls documents/*.txt | wc -l).files
# This yields name like 2.files, 3.files, etc...
# .PHONY $(NUMBER) -- NOT a phony target!

$(NUMBER):
        rm *.files    # Remove previous trigger
        touch $(NUMBER)

index.txt: $(NUMBER)
        ...generate index.txt...

- , . , , . :

NUMBER=$(shell ls -l documents/*.txt | md5sum | sed 's/[[:space:]].*//').files

-l - , , . Bu, , .

: sed , md5sum -.

+6

, .

list.txt: documents
        ls documents/*.txt 2>/dev/null > $@ || true

, , , make .

+2

Here is a solution that updates the index if and only if the set of files has changed:

list.txt.tmp: documents
    ls $</*.txt > $@

list.txt: list.txt.tmp
    cmp -s $< $@ || cp $< $@

index.txt: list.txt
    ...generate index.txt...

Thanks to "cmp || cp", the time ctime "list.txt" does not change if the result of "ls" has not changed.

0
source

Source: https://habr.com/ru/post/1737096/


All Articles