DEV Community

Michele Caci
Michele Caci

Posted on

TIL: Find alone and find within loops in a shell

Today I learned a situation in which is good to use a for loop in a shell in moments when the -exec flag alone is difficult to use.

The find command in any case is very powerful and can assist in many shell tasks. Usually when executing commands on a set of file the find command, together with the -exec expression in the find $PATH -exec $COMMAND {} \; instruction, is very useful to write short and meaningful operations like

find ./ -name $PATTERN -exec cat {} \;
Enter fullscreen mode Exit fullscreen mode

to print the content of a list of files denoted by the PATTERN variable.

However, it is not very useful when the situation gets complex like in this scenario.

Suppose we have 2 files:

  1. file1 with content

    -l

  2. file2 with content

    -a

And we want to run ls with the options found in these files.

In this context the command

find ./ -name "file*" -exec ls $(cat {}) \;
Enter fullscreen mode Exit fullscreen mode

would not work (the error would be "cat: {}: No such file or directory").

In this situation a classic for range loop will help us achieve this goal. As in this example

for i in $(find ./ -name "file*"); do ls $(cat $i); done
Enter fullscreen mode Exit fullscreen mode

Despite being very unconventional uses of those instructions, I propose these examples to draw a line on where the find command manages to do the job alone and where it is more helpful to include its resuls it in a for range loop.

Hope this was helpful, thanks a lot for your time reading it!

Top comments (0)