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!

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

AWS Security LIVE!

Tune in for AWS Security LIVE!

Join AWS Security LIVE! for expert insights and actionable tips to protect your organization and keep security teams prepared.

Learn More

👋 Kindness is contagious

Discover a treasure trove of wisdom within this insightful piece, highly respected in the nurturing DEV Community enviroment. Developers, whether novice or expert, are encouraged to participate and add to our shared knowledge basin.

A simple "thank you" can illuminate someone's day. Express your appreciation in the comments section!

On DEV, sharing ideas smoothens our journey and strengthens our community ties. Learn something useful? Offering a quick thanks to the author is deeply appreciated.

Okay