Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Process files recursively using bash

I currently have a small script that processes all files in a directory. I would like this to also recursively process all files in the subfolder. Any thoughts on how to do this? My current code is:

#!/bin/bash
for file in ./input/*
do
   do_something "$file"
done
like image 729
user1769925 Avatar asked Jan 30 '26 12:01

user1769925


2 Answers

You can use find:

find input/ -type f -exec do_something {} \;

From the man page:

The find utility recursively descends the directory tree for each path listed, evaluating an expression (composed of the primaries and operands listed below) in terms of each file in the tree.

For clarity, here's some more detail from the man page about exec and {}:

-exec utility [argument ...] ;

True if the program named utility returns a zero value as its exit status.

Optional arguments may be passed to the utility. The expression must be terminated by a semicolon (;). If you invoke find from a shell you may need to quote the semicolon if the shell would otherwise treat it as a control operator. If the string {} appears anywhere in the utility name or the arguments it is replaced by the pathname of the current file. Utility will be executed from the directory from which find was executed. Utility and arguments are not subject to the further expansion of shell patterns and constructs.

Hope this helps :)

like image 192
Darragh Enright Avatar answered Feb 01 '26 12:02

Darragh Enright


In bash 4, you can use the ** pattern, which matches 0 or more directories in a path.

shopt -s globstar
for file in ./input/**/*
do
   do_something "$file"
done
like image 20
chepner Avatar answered Feb 01 '26 12:02

chepner



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!