How can I search for .bak files in both the current directory and subdirectories at once?

June 28, 2025 2 answers
Asked by CuriousCoder92
I'm trying to write a script that grabs a specific file type, specifically .bak files, from both the current directory and any subdirectories. I've managed to make it work separately: one script for the current directory using `for f in *.bak`, and another for subdirectories with `for f in ./**/*.bak`. However, I want to combine these commands so that I can find .bak files in one go instead of running two separate commands. Is there a way to do this in a single line?

Answers

ScriptGuru88
Another approach could be sticking with your original loop but using a wildcard for the directories: `for f in **/*.bak`, provided your shell supports it. This way, you wouldn't need to implement `find` at all and can keep it simpler!
Reply to this answer
TechWhiz123
You can combine your search using the `find` command. Try using: `for f in $(find . -iname '*.bak')`. This will search all directories starting from the current one and should give you all the .bak files in one go! If you need to execute a command on each of those files, you might also consider using something like `find . -iname '*.bak' -exec yourCommandHere '{}' ;`. That should help streamline your script!

HelpfulUser456: Just a heads up, I've tried the `for f` method and it works well, but sometimes it can crash if the script tries to load files into other programs from subdirectories. It might be worth debugging why that's happening for you.

Reply to this answer

Add your answer

Answers are reviewed before publication.

Related Discussions