Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

simple loop over files in some directory makefile

Tags:

bash

makefile

ls

I can easily print all the files inside some directory from bash:

$ cat go.sh
BASEDIR=~/Downloads
MYDIR=${BASEDIR}/ddd
for f in $(ls ${MYDIR}); do echo $f; done

$ ./go.sh
m.txt
d.txt

When I try to do a similar thing from makefile it doesn't work well:

$ cat makefile
BASEDIR = ${HOME}/Downloads
MYDIR = ${BASEDIR}/ddd
all:
    for f in $(ls ${MYDIR}); do echo ${f}; done

$ make
for f in ; do echo ; done

And here is another trial that doesn't work:

$ cat makefile
BASEDIR = ${HOME}/Downloads
MYDIR = ${BASEDIR}/ddd
all:
    for f in $(shell ls ${MYDIR}); do echo ${f}; done

$ make
for f in d.txt m.txt; do echo ; done
like image 315
OrenIshShalom Avatar asked Jan 03 '19 10:01

OrenIshShalom


People also ask

How do I loop all files in a directory?

To loop through a directory, and then print the name of the file, execute the following command: for FILE in *; do echo $FILE; done.

How do you loop through all the files in a directory in bash?

The syntax to loop through each file individually in a loop is: create a variable (f for file, for example). Then define the data set you want the variable to cycle through. In this case, cycle through all files in the current directory using the * wildcard character (the * wildcard matches everything).

What does $() mean in Makefile?

The $@ and $< are called automatic variables. The variable $@ represents the name of the target and $< represents the first prerequisite required to create the output file.


1 Answers

Maybe you can do it purely Makefile way?

MYDIR = .
list: $(MYDIR)/*
        @echo $^

You can still run command from Makefile like this

MYDIR = .
list: $(MYDIR)/*
        for file in $^ ; do \
                echo "Hello" $${file} ; \
        done

If I were you, I'd rather not mix Makefile and bash loops based on $(shell ...). I'd rather pass dir name to some script and run loop there - inside script.

like image 155
Oo.oO Avatar answered Nov 10 '22 13:11

Oo.oO