Don't loop over find's output

Several days ago, I needed to update some of my projects. The changes were mostly the same and needed to be applied to the same files every time. In some cases, I also had to copy certain files to specific directories with the same name. This was a task that could have been done more efficiently and quickly with a script.

To simplify the explanation, let's say that I wanted to copy the same file to directories with the same name, such as "src". Our projects were organized as follows:

 1.
 2├── project1
 3│   └── somedir
 4│       └── src
 5├── project2
 6│   └── src
 7└── project3
 8    └── somedir
 9        └── some other
10            └── src

I started searching for a solution and found myself tangled in a strange web of for and while loops, as well as exotic uses of the mapfile command. At first glance, these solutions didn't convince me. Nevertheless, I decided to loop over the mapfile output, using something like the following code:

1mapfile -d $'\0' FILES < <(find . -name "src")

and loop the content of the $FILES array. It seemed nice and easy, but something bad was about to happen: one of the directories contained a space. This can be a major problem when iterating through an array in bash.

I started to figure out how to solve this issue, and began to cobble something together. But then I stopped and thought to myself, 'Wait a minute, it can't be this difficult to solve such a simple task.' I knew there was something I was missing, something buried deep in my mind, but I just couldn't recall it. I don't know if this happens to you, but at that moment I realized that the solution was probably very easy, and I was only wasting time.

Finally, I decided to do a search on DuckDuckGo (yes, I know, we usually say 'search on Google,' but it's not the only search engine out there!). That's when I came across this article, and had my 'aha' moment - the solution was as simple as I had thought.

1find . -name src -exec cp file {} \;

And I obtained:

 1.
 2├── file
 3├── project1
 4│   └── somedir
 5│       └── src
 6│           └── file
 7├── project2
 8│   └── src
 9│       └── file
10└── project3
11    └── somedir
12        └── some other
13            └── src
14                └── file

Of course, my situation was far more complex than this - I didn't just have to copy a file. However, the purpose of this short story is to help people who, like me, have to perform similar tasks, and to save them from wasting time on something that should be easy.

I hope you enjoyed this post, if you want to share it to your contacts on the social media, you can do it by clicking on the social icons at the beginning of this post, otherwise you can copy the url and share it wherever you like.

If you want to reach me, you will find all my contacts in the About page. Sooner or later I will enable comments on my posts, in the meantime, if you have questions, contact me, I'll be happy to answer.