Skip to main content
ubuntuask.com

Back to all posts

How to Loop Through Files In A Directory In Bash?

Published on
6 min read
How to Loop Through Files In A Directory In Bash? image

Best Script Automation Tools to Buy in March 2026

1 Javascript of Automation: Crafting Scripts for macOS (Aquitaine Programming)

Javascript of Automation: Crafting Scripts for macOS (Aquitaine Programming)

BUY & SAVE
Save 57%
Javascript of Automation: Crafting Scripts for macOS (Aquitaine Programming)
2 MASTERING PYTHON FOR AUTOMATION: Simplify Repetitive Tasks with Python Scripts and Tools

MASTERING PYTHON FOR AUTOMATION: Simplify Repetitive Tasks with Python Scripts and Tools

BUY & SAVE
MASTERING PYTHON FOR AUTOMATION: Simplify Repetitive Tasks with Python Scripts and Tools
3 Python For Automation: Makes Your Life Better

Python For Automation: Makes Your Life Better

BUY & SAVE
Python For Automation: Makes Your Life Better
4 Build AI Apps with Google Apps Script: APIs, Gemini, and Real-World Automation for Sheets, Docs, and Web Apps

Build AI Apps with Google Apps Script: APIs, Gemini, and Real-World Automation for Sheets, Docs, and Web Apps

BUY & SAVE
Build AI Apps with Google Apps Script: APIs, Gemini, and Real-World Automation for Sheets, Docs, and Web Apps
5 The ADHD Money Map: Automations, Impulse Control Tools, and Budgeting That Doesn't Fail (The Practical ADHD Toolkit)

The ADHD Money Map: Automations, Impulse Control Tools, and Budgeting That Doesn't Fail (The Practical ADHD Toolkit)

BUY & SAVE
The ADHD Money Map: Automations, Impulse Control Tools, and Budgeting That Doesn't Fail (The Practical ADHD Toolkit)
6 Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools

BUY & SAVE
Save 27%
Learn PowerShell Scripting in a Month of Lunches, Second Edition: Write and organize scripts and tools
7 101 Ultimate ChatGPT Prompts for Realtors: The Complete AI Toolkit for Real Estate Success: AI-Powered Scripts for Listing Descriptions, Social Media, Lead Generation, Marketing & Client Follow‑Ups

101 Ultimate ChatGPT Prompts for Realtors: The Complete AI Toolkit for Real Estate Success: AI-Powered Scripts for Listing Descriptions, Social Media, Lead Generation, Marketing & Client Follow‑Ups

BUY & SAVE
101 Ultimate ChatGPT Prompts for Realtors: The Complete AI Toolkit for Real Estate Success: AI-Powered Scripts for Listing Descriptions, Social Media, Lead Generation, Marketing & Client Follow‑Ups
8 Agentic AI Staging: The Unfair Advantage: The Residential DIY Guide to Virtual Staging. 400 Exact Prompts for ChatGPT, Gemini & Grok to Save Thousands per Listing.

Agentic AI Staging: The Unfair Advantage: The Residential DIY Guide to Virtual Staging. 400 Exact Prompts for ChatGPT, Gemini & Grok to Save Thousands per Listing.

BUY & SAVE
Agentic AI Staging: The Unfair Advantage: The Residential DIY Guide to Virtual Staging. 400 Exact Prompts for ChatGPT, Gemini & Grok to Save Thousands per Listing.
9 Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools

Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools

  • QUALITY ASSURANCE: GUARANTEED GOOD CONDITION FOR A POSITIVE BUY.
  • AFFORDABLE PRICING: SAVE MONEY ON GREAT QUALITY USED BOOKS.
  • ECO-FRIENDLY CHOICE: SUPPORT RECYCLING BY BUYING USED BOOKS.
BUY & SAVE
Save 8%
Windows 7 and Vista Guide to Scripting, Automation, and Command Line Tools
10 Shelly 1 Mini Gen3 | WiFi Smart Switch Relay 1 Channel 8A | Home Automation | Bluetooth Gateway | Compatible with Alexa & Google Home | iOS Android App | No Hub Required | Dry Contacts

Shelly 1 Mini Gen3 | WiFi Smart Switch Relay 1 Channel 8A | Home Automation | Bluetooth Gateway | Compatible with Alexa & Google Home | iOS Android App | No Hub Required | Dry Contacts

  • COMPACT DESIGN: INSTALL ANYWHERE FOR INSTANT SMART CONTROL.
  • RELIABLE GARAGE DOOR CONTROL: REMOTELY OPERATE WITH 8A CAPACITY.
  • SMART IRRIGATION AUTOMATION: WEATHER-BASED CONTROL FOR EFFICIENCY.
BUY & SAVE
Shelly 1 Mini Gen3 | WiFi Smart Switch Relay 1 Channel 8A | Home Automation | Bluetooth Gateway | Compatible with Alexa & Google Home | iOS Android App | No Hub Required | Dry Contacts
+
ONE MORE?

In Bash, you can loop through files in a directory using a combination of the for loop and the wildcard character (*).

Here's an example of how you can loop through files in a directory:

for file in /path/to/directory/*; do echo "$file"

Perform operations on the file

done

Let's break down the code:

  • for file in /path/to/directory/*; do: This sets up a loop that assigns each file in the specified directory (/path/to/directory/) to the variable file. The * acts as a wildcard character, matching any file within the directory.
  • echo "$file": This line prints the filename to the terminal. You can modify it to perform other operations on the file.
  • # Perform operations on the file: This comment indicates the area where you can include your desired operations to be applied on each file.

You can replace /path/to/directory/ with the actual path to the directory you want to iterate through.

This way, the loop will go through each file in the directory and perform the specified operations.

How to list all files in a directory using Bash script?

To list all files in a directory using a Bash script, you can use the combination of ls command with appropriate options. Here's an example script:

#!/bin/bash

Set the directory path

dir="/path/to/directory"

List all files in the directory

files=$(ls -p "$dir" | grep -v /)

Iterate over each file and print its name

for file in $files do echo $file done

Make sure to replace "/path/to/directory" with the actual directory path you want to list files from. The script uses the ls command with the -p option to display a slash ('/') after each directory name and the grep command with the -v option to exclude directories from the output. The resulting list of files is stored in the files variable, which is then iterated over in a loop to print each file's name.

How to perform an action on each file in a directory using Bash?

To perform an action on each file in a directory using Bash, you can use a loop. Here's an example:

#!/bin/bash

Specify the directory

directory="/path/to/directory"

Loop through each file in the directory

for file in "$directory"/*; do # Perform your action here echo "Processing file: $file" done

In this example, replace /path/to/directory with the actual directory path where the files are located. The for loop will iterate through each file in the directory, and you can perform any desired action within the loop. In this case, we're simply echoing the file name.

What is the difference between the Bash for loop and while loop?

The main difference between the Bash for loop and while loop lies in how they iterate.

The Bash for loop allows you to iterate over a specific range or a list of elements. It follows the syntax:

for item in list do commands done

Here, "item" takes each value from the "list," one at a time, and executes the commands specified within the loop. This loop is helpful when you know the range or have a fixed set of elements to iterate.

On the other hand, the Bash while loop repeatedly executes a set of commands until a certain condition becomes false. It follows the syntax:

while [ condition ] do commands done

In this case, the loop keeps executing the "commands" as long as the "condition" evaluates to true. The "condition" is typically a comparison or a check on a variable. This loop is useful when you want to keep repeating a task until a particular condition is met.

To summarize, the for loop is suitable when you want to iterate over a known range or list, while the while loop is appropriate for continuous execution until a specific condition is satisfied.

What is the difference between relative and absolute paths in Bash?

In bash, relative and absolute paths are used to specify the location of a file or directory.

  • Absolute Path: An absolute path provides the full and complete path to a file or directory starting from the root directory ("/"). It includes all the directories in the hierarchy leading up to the desired file or directory. For example, "/home/user/documents/file.txt" is an absolute path. This path remains constant regardless of the current working directory.
  • Relative Path: A relative path specifies the location of a file or directory relative to the current working directory. It does not start with the root directory and relies on the current working directory as a reference point. For example, if the current working directory is "/home/user", a relative path like "documents/file.txt" would refer to "/home/user/documents/file.txt". The relative path changes based on the current working directory.

In summary, the main difference between relative and absolute paths is that the absolute path specifies the complete path from the root directory, while the relative path specifies the path relative to the current working directory.

How to append text to a file using Bash?

To append text to a file using Bash, you can use the >> or echo command. Here are two approaches:

  1. Using >>: echo "Text to append" >> filename.txt This command will append the "Text to append" to the end of the filename.txt file. If the file doesn't exist, it will create a new file.
  2. Using echo with >>: echo "Text to append" >> filename.txt This command works similarly to the first approach, but it explicitly uses the echo command to print the text to the file.

Make sure to replace filename.txt with the actual name of the file you want to append the text to.

How to execute a Bash script in the background?

To execute a Bash script in the background, you can use the following steps:

  1. Open a Terminal.
  2. Navigate to the directory where your Bash script is located using the cd command. For example, cd /path/to/script.
  3. Run the Bash script using the ./ prefix followed by the script name. For example, ./script.sh &. The & symbol at the end runs the script in the background. Ensure that the script has execute permissions. If not, you can give execute permission using the chmod +x script.sh command.
  4. Press Enter to execute the script in the background.

The script will now start executing in the background, allowing you to continue using the Terminal or run other tasks simultaneously.