bash loop through files in directory

Bash Loop Through Files in Directory Recursively

Often you may need to loop through files in directory recursively, in terminal or shell script. In this article, we will learn how to loop through files in directory recursively in Linux. You can use these steps on almost every shell in Linux.


Bash Loop Through Files in Directory Recursively

Find is one of the best commands to find files that satisfy specific criteria. Here is the command to find all files in your present working directory.

$ find . -type f -print0

In the above command we use dot(.) to specify that we want to find files in our present working directory. You can specify another directory if you want to search in another folder.

$ find /home/data -type f -print0

We also use -type f to specify that we want to search for only files and not folders.

The above command will display a list of all relative file paths. We use the output of above command in a for loop to iterate through these files and work with them. In the following code, you can fill the part between do…done with code to work with files. We use -print0 option to display all filenames even if it includes spaces and other special characters. If you use only -print option, it will not work with files with spaces & special characters.

for i in $(find . -type f -print0)
do
    #code to perform task on each file
done

If you want to find specific types of files such as pdf files, you can use -name option in your find command as shown below. For the name option, you can specify the file extension name formats using wildcard characters.

for i in $(find . -type f -print0 -name "*.pdf")
do
 
    #code to perform task on each file
done

Similarly, here is an example to search for pdf and .doc files in your folder.

for i in $(find . -type f -print0 -name "*.pdf" or -name ".doc")
do
     
    #code to perform task on each file
done

You can run the above command directly on terminal, or add it as a part of your shell script.

Also read:

How to Reset Local Git Repository To Remote
Cannot Access NGINX From Outside
How to Undo Git Rebase
How to Stop Tracking Folder in Git Without Deleting
Bash Loop Through Files in Directory & Subdirectory

Leave a Reply

Your email address will not be published.