shell script to loop through files in directory

Shell Script to Loop Through Files in a Directory

Sometimes you may need to loop through files in a folder or subfolder to perform an operation on each file separately. Here is a shell script to loop through files in a directory. You can use it as a template to build your own script to perform any kind of operations as per your requirement.


Shell Script to Loop Through Files in a Directory

Here are the steps to create a shell script to loop through files in a directory.


1. Create empty script

Open terminal and run the following command to create an empty shell script file.

$ sudo vi loop_file.sh


2. Add shell script to loop through files in directory

Add the following lines to your shell script file.

#!/bin/bash

FILES="$1/*"
for f in $FILES
do
  echo "Processing $f file..."
  # take action on each file. $f store current file name
  # perform some operation with the file
done

In the above code we store folder path in $FILE shell variable. $1 is used to capture folder path provided via command line argument. This allows us to use the script for any folder location on our system.

If you want to loop through files in the same folder always, then replace $1 with the path to your folder e.g. /home/data

FILES="/home/data"

Then we will loop through it using for..do..done statement. Here we use $f shell variable to store current file name. You may write shell commands to use the file in do..done section.

Save and close the file.


3. Make shell script executable

Run the following command to make the shell script executable.

$ sudo chmod +x loop_file.sh


4. Test shell script

Run your shell script on different folders to loop through their files. Please do not add trailing slash after the folder path, since we already add it in our script.

$ ./loop_file.sh /home/ubuntu/project

$ ./loop_file.sh /home/data

That’s it. We have created shell script to iterate through files in a folder. You can use it to work with files in a folder and do different kinds of tasks with them.

Also read:

How to Loop Over Lines of File in Bash
How to Check if Directory Exists in Shell Script
Shell Script to Delete Files in Directory
VirtualHost for Wildcard Subdomains in Apache
Shell Script To Tar Multiple Files & Directories

Leave a Reply

Your email address will not be published. Required fields are marked *