DEV Community

Michele Caci
Michele Caci

Posted on

2 2

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!

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more