Looping Through Files and Directories

Su Suriya Ravichandran Updated 06 Dec 2026
11 min read ·Lesson 82 of 205

One of the most common jobs for a Bash script is to do the same thing to many files: rename them, copy them, count them, check their size, convert them. The standard tool for this is a for loop (lesson 78) whose list comes from a glob pattern (lesson 52). The shell expands the pattern into the matching file names before the loop starts, and the loop then runs once for each name.

This lesson builds on that idea. It shows the safe way to write such loops, how to handle names with spaces, what happens when nothing matches, how to separate files from directories, and how to reach files in sub-folders.

The Sample Folder

The examples in this lesson use the following folder. The names include a file with a space, a hidden file and a few sub-folders:

project/
├── notes.txt
├── todo.txt
├── meeting notes.txt
├── report.pdf
├── .hidden.txt
├── docs/        (a.md, b.md)
├── src/         (main.c, util.c, util.h)
└── my notes/    (x.txt)

A Basic File Loop

for f in *.txt; do
    echo "file: $f"
done

Output:

file: meeting notes.txt
file: notes.txt
file: todo.txt

How It Works

The pattern *.txt is not given to the loop as text. Before the loop runs, Bash replaces the pattern with a sorted list of the matching names in the current directory. The loop then assigns the names one at a time to f. Three details are worth noticing:

  • The pattern matched meeting notes.txt as one name, even though it contains a space. Expansion of a glob produces separate words for separate files, so a space inside a name does not split it.
  • The hidden file .hidden.txt was not listed, because * does not match names that start with a dot (see the section on hidden files below).
  • The result is sorted in the order of the shell's locale. In the C locale that means uppercase letters come before lowercase letters, so B.txt is listed before a.txt. Other locales may sort differently.

Quote the Variable Inside the Loop

The loop above was safe because the glob already produced correct words. The danger starts in the body. If you use the variable without quotes, Bash splits it on spaces again (lessons 53 and 55):

for f in *.txt; do ls -l $f 2>&1 | head -1; done

Output (the owner and date depend on your system, and head -1 keeps only the first line of each ls result):

ls: cannot access 'meeting': No such file or directory
-rw-r--r-- 1 root root 0 Nov 21 14:53 notes.txt
-rw-r--r-- 1 root root 0 Nov 21 14:53 todo.txt

For the file meeting notes.txt, the unquoted $f became two arguments, meeting and notes.txt, so ls looked for a file named meeting. The corrected command is ls -l "$f". Make quoting the variable a habit in every loop body:

for f in *.txt; do printf '[%s] has %s characters\n' "$f" "${#f}"; done

Output:

[meeting notes.txt] has 17 characters
[notes.txt] has 9 characters
[todo.txt] has 8 characters

The expression ${#f} gives the length of the value (lesson 54). Brackets around the name in the output make any hidden spaces visible, which is a handy debugging trick.

When Nothing Matches

If a glob matches no files, Bash leaves the pattern unchanged. The loop then runs once, with the pattern itself as the value:

for f in *.zip; do echo "got: $f"; done

Output:

got: *.zip

This is a surprise for many beginners: the loop body ran even though no .zip file exists, and a command such as unzip "$f" would then fail on a file literally named *.zip. There are two common ways to handle this.

Test That the File Exists

The first way is to check each value with -e (lesson 71). If the file does not exist, skip the loop:

for f in *.zip; do
    [ -e "$f" ] || { echo "no zip files"; break; }
    echo "$f"
done

Output:

no zip files

The test fails for the literal *.zip, so the || branch prints a message and leaves the loop with break (lesson 84). When files do exist, the test succeeds on every name and the loop works normally. The continue command (lesson 84) is the alternative if you want to skip the item but keep looping.

Turn On nullglob

The second way is the Bash option nullglob, which makes a pattern with no matches expand to nothing. The loop then runs zero times:

shopt -s nullglob
for f in *.zip; do echo "got: $f"; done
echo "(loop body skipped)"
shopt -u nullglob

Output:

(loop body skipped)

The shopt -s command switches the option on and shopt -u switches it off again (lesson 149 covers shopt in depth). Use nullglob in Bash scripts when you want empty results to mean "nothing to do". It is a Bash feature and is not available in Dash.

Looping Over Directories

A pattern that ends with a slash matches only directories. The trailing slash stays in the value:

for d in */; do echo "dir: $d"; done
for d in */; do echo "name: ${d%/}"; done

Output:

dir: docs/
dir: my notes/
dir: src/
name: docs
name: my notes
name: src

The expression ${d%/} removes one trailing slash from the end of the value (lesson 54), which is useful when you want to build names such as "${d%/}.bak".

Separating Files from Directories

Sometimes you want to process everything in a folder but treat files and directories differently. Loop over * and use the file tests from lesson 72:

for item in *; do
    if [ -d "$item" ]; then echo "directory: $item"
    elif [ -f "$item" ]; then echo "file:      $item"
    fi
done

Output:

directory: docs
file:      meeting notes.txt
directory: my notes
file:      notes.txt
file:      report.pdf
directory: src
file:      todo.txt

The test -d is true for directories and -f is true for regular files. Anything else (a socket, a broken link) is skipped because neither branch matches.

Hidden Files

The * pattern does not match a name that begins with a dot. Running the loop earlier found no .hidden.txt at all:

for f in *; do echo "star: $f"; done | grep -c hidden

Output:

0

To include hidden files you have two choices. The first is to switch on the dotglob option:

shopt -s dotglob
for f in *; do echo "dotglob: $f"; done | grep hidden
shopt -u dotglob

Output:

dotglob: .hidden.txt

The second is to write a second pattern that matches names starting with a dot. The pattern .[!.]* means "a dot, then one character that is not a dot, then anything", which skips the special entries . and ..:

for f in .[!.]*; do echo "dot pattern: $f"; done

Output:

dot pattern: .cache
dot pattern: .hidden.txt

With dotglob on, * also matches names that start with a dot, so all entries are included in one loop. In Bash 5.2 the pattern .* also skips . and .., but older versions include them, which is why .[!.]* is the more portable form.

Looping Over Files in Another Directory

Put the directory in front of the pattern. The value of the loop variable then contains the whole path:

dir=src
for f in "$dir"/*; do echo "$f -> ${f##*/}"; done

Output:

src/main.c -> main.c
src/util.c -> util.c
src/util.h -> util.h

The directory variable is quoted, but the * must stay outside the quotes, otherwise it would be treated as a literal asterisk. The expression ${f##*/} removes the longest prefix that ends in a slash, which leaves only the file name (lesson 54).

Several Patterns in One Loop

A for list may contain several patterns. They expand one after the other:

for f in *.txt *.pdf; do echo "$f"; done

Output:

meeting notes.txt
notes.txt
todo.txt
report.pdf

Each pattern is sorted separately, so the .txt files come first and the .pdf file last.

Working with Names and Extensions

Parameter expansion makes it easy to change the extension while keeping the base name. This loop copies every text file to a backup with the extension .bak:

for f in *.txt; do cp -- "$f" "${f%.txt}.bak"; done
ls *.bak

Output:

meeting notes.bak
notes.bak
todo.bak

The expression ${f%.txt} removes the shortest matching suffix .txt from the end of the value, so notes.txt becomes notes and the new name is notes.bak. The two hyphens after cp mark the end of the options, so that a file whose name starts with a dash is not mistaken for an option.

A loop is also a natural way to produce a small report. This one prints the size of each C source file (the two sample files here contain 29 and 40 bytes):

for f in src/*.c; do printf '%-12s %s bytes\n' "$f" "$(wc -c < "$f")"; done

Output:

src/main.c   29 bytes
src/util.c   40 bytes

The format %-12s pads the name to 12 characters on the left-aligned side, and $(wc -c < "$f") is a command substitution (lesson 48) that reads the file through input redirection, so wc prints only the number and not the file name.

You can also count matches with a variable that grows inside the loop:

count=0
for f in *.txt; do count=$((count + 1)); done
echo "$count text files"

Output:

3 text files

Names That Begin with a Dash

A file called -n.txt is matched by *.txt, and then it can be mistaken for an option by the command in the loop body:

touch -- -n.txt
for f in *.txt; do echo "plain: $f"; done | head -3
for f in ./*.txt; do echo "safe: $f"; done | head -3

Output:

plain: -n.txt
plain: meeting notes.txt
plain: notes.txt
safe: ./-n.txt
safe: ./meeting notes.txt
safe: ./notes.txt

Starting the pattern with ./ makes every value begin with ./, so no name can look like an option. For commands that accept it, -- before the arguments does the same job. Using ./* is the habit to adopt for loops that feed names to rm, mv, cp and similar commands. Lessons 111 and 161 return to this topic.

Files in Sub-Folders

A plain * stays inside one folder. To reach files at any depth you can turn on the globstar option, which gives ** the meaning "this folder and all folders below it":

shopt -s globstar
for f in **/*.md; do echo "md: $f"; done
for f in **/*.c; do echo "c: $f"; done
shopt -u globstar

Output:

md: docs/a.md
md: docs/b.md
c: src/main.c
c: src/util.c

The **/ part matches any number of directory levels, including none. globstar is a Bash feature (available from Bash 4) and is not part of POSIX shells.

For a portable and fully safe approach, let find produce the names and separate them with null characters, which cannot appear in a file name. The read command can split on that character with -d '':

find . -name '*.txt' -type f -print0 | sort -z | while IFS= read -r -d '' f; do echo "found: $f"; done

Output:

found: ./.hidden.txt
found: ./meeting notes.txt
found: ./my notes/x.txt
found: ./notes.txt
found: ./todo.txt

This loop found the hidden file and the file in the sub-folder, and it handled the space correctly. There is one catch: because the loop is on the right side of a pipe, it runs in a subshell, so variables changed inside it are lost afterwards (see lessons 61 and 80). Feeding the loop with process substitution keeps the loop in the current shell:

n=0
while IFS= read -r -d '' f; do n=$((n+1)); done < <(find . -name '*.txt' -type f -print0)
echo "n=$n"

Output:

n=5

Lesson 83 explains this technique in detail, and lesson 112 combines find -print0 with xargs -0.

Nested Loops over Folders and Their Contents

A loop inside a loop can look at the contents of several directories. This one counts the entries in each sub-folder:

for d in docs src "my notes"; do
    n=0
    for f in "$d"/*; do [ -e "$f" ] && n=$((n+1)); done
    echo "$d: $n items"
done

Output:

docs: 2 items
src: 3 items
my notes: 1 items

The -e test inside protects against an empty folder, where the glob would stay unexpanded and the loop would count the pattern itself. Lesson 85 covers nested loops in more detail.

A glob matches the names of links just as it matches ordinary files, and the file tests follow the link:

ln -s notes.txt link.txt
for f in link.txt; do
    [ -L "$f" ] && echo "$f is a symlink"
    [ -f "$f" ] && echo "$f resolves to a regular file"
done

Output:

link.txt is a symlink
link.txt resolves to a regular file

-L asks whether the name itself is a link, while -f follows the link and asks about the target. Both can be true at once, as shown here. If a script must treat links specially, test -L first.

Portability

The plain loops, [ -e ], [ -d ], [ -f ], ${f%.txt} and ${f##*/} work in Dash and every other POSIX shell. A glob with no match also stays literal in Dash:

#!/bin/sh
for f in *.txt; do echo "[$f]"; done
for f in *.zip; do echo "got $f"; done

With two text files and no zip files, Dash prints the two names, and then got *.zip. The Bash-only features from this lesson are shopt (with nullglob, dotglob and globstar) and process substitution. Dash also rejects read -d, and prints Illegal option -d, so the null-separated loop needs Bash. Scripts written for sh can use the [ -e "$f" ] || continue guard instead of nullglob (lessons 188 and 189).

0 Comments

Reviewed before they appear

No comments yet.

Bash
Introduction to Bash What Is a Shell? What Is Bash (Bourne Again Shell)? Bash vs. Shell vs. Terminal Bash vs. sh, Zsh, and Fish Where Bash Is Used: Linux, DevOps, and Automation Installing Bash on Linux Using Bash on macOS Using Bash on Windows with WSL Checking Your Bash Version Opening and Using a Terminal Running Your First Bash Command Understanding Command Syntax and Arguments Bash Built-in Commands vs. External Commands Working with pwd, ls, and cd Creating Files and Directories with touch and mkdir Copying, Moving, and Renaming Files Removing Files and Directories Safely Viewing Files with cat, less, head, and tail Searching for Files with find Searching Text with grep Understanding File Paths and Wildcards Using man Pages and Command Help Bash Script Structure Creating Your First Bash Script Understanding the Shebang (#!/usr/bin/env bash) Making a Script Executable with chmod Running a Bash Script in Different Ways Writing Comments in Bash Using echo and printf Reading User Input with read Displaying Helpful Messages in Scripts Using Semicolons and Newlines Bash Variables: Declaration and Usage Rules for Naming Bash Variables Environment Variables Local Variables vs. Environment Variables Exporting Variables with export Common Environment Variables: HOME, PATH, USER, and PWD Read-Only Variables with readonly Removing Variables with unset Command-Line Arguments: $0, $1, and More Special Parameters: $#, $?, $$, $!, $@, and $* Positional Parameters and shift Default Values with Parameter Expansion Single Quotes vs. Double Quotes Escaping Special Characters Command Substitution with $(...) Arithmetic Expansion with $((...)) Brace Expansion Tilde Expansion and Home Directories Filename Expansion and Globbing Understanding Word Splitting Parameter Expansion Basics Why Quoting Variables Matters Standard Input, Standard Output, and Standard Error Redirecting Output with > and >> Redirecting Input with < Redirecting Errors with 2> Combining Standard Output and Standard Error Using Pipes (|) to Connect Commands Using tee to Save and Display Output Here Documents with << Here Strings with <<< Command Lists with ;, &&, and || Conditional Statements with if, then, and fi Using elif and else Testing Conditions with test and [ ] Using [[ ]] for Bash Conditionals Comparing Strings in Bash Checking Whether Files Exist Checking File Types and Permissions Integer Comparisons in Bash Logical Operators: &&, ||, and ! Using case Statements Pattern Matching in case Common Conditional Statement Mistakes for Loops in Bash C-Style for Loops while Loops until Loops Looping Through Files and Directories Looping Through Command Output Safely break and continue Nested Loops select Loops for Simple Menus Avoiding Infinite Loops Defining and Calling Bash Functions Passing Arguments to Functions Returning Status Codes from Functions Understanding return vs. echo in Functions Local Variables in Functions Function Scope and Variable Visibility Organizing Scripts into Functions Sourcing Other Bash Files with source Reusable Bash Utility Functions Indexed Arrays in Bash Creating and Accessing Array Elements Adding and Removing Array Elements Looping Through Arrays Array Length and Indices Associative Arrays in Bash Iterating Over Associative Arrays Passing Arrays to Functions Common Array Pitfalls Processing Text with grep, sed, and awk Using cut, sort, uniq, and wc Finding and Replacing Text with sed Extracting Columns with awk Parsing CSV-Like Text from the Command Line Working with Filenames That Contain Spaces Safe File Handling with find -print0 and xargs -0 Temporary Files with mktemp Reading Files Line by Line Appending Logs to a File Understanding Exit Codes Checking Command Success with $? Using exit to End a Script Fail-Fast Scripts with set -e: Benefits and Caveats Using set -u and set -o pipefail Combining Strict Mode Options Safely Handling Errors with if Statements Traps with trap Cleaning Up Temporary Files on Exit Writing Useful Error Messages Debugging Scripts with bash -x Parsing Script Arguments Validating Required Arguments Handling Optional Arguments Parsing Options with getopts Building Help Messages with --help Setting Defaults for Optional Parameters Handling Unknown Options and Invalid Input Creating Interactive Menus in Bash Foreground and Background Processes Running Commands in the Background with & Managing Jobs with jobs, fg, and bg Waiting for Processes with wait Capturing Process IDs with $! and $$ Sending Signals with kill Handling Interrupts and Termination Signals Running Commands with timeout Basic Process Monitoring from Bash Aliases and Shell Functions: When to Use Each Customizing the Bash Prompt (PS1) Bash Startup Files: .bashrc, .bash_profile, and Profile Interactive vs. Non-Interactive Bash Shell Options with set shopt: Enabling Bash-Specific Options Directory Stack with pushd, popd, and dirs Process Substitution with <(...) and >(...) Advanced Parameter Expansion Pattern Matching and Extended Globbing Bash Script Security Fundamentals Avoiding Command Injection in Shell Scripts Quoting User Input Safely Why eval Is Risky and Safer Alternatives Handling Secrets and Credentials in Scripts Using Least Privilege in Automation Scripts Safe Use of rm and Destructive Commands Validating Paths and User-Supplied Filenames ShellCheck: Static Analysis for Bash Scripts Writing Readable and Maintainable Bash Automating Backups with Bash Creating Log Rotation and Cleanup Scripts Checking Disk Usage and Free Space Monitoring CPU, Memory, and System Load Checking Website Availability with curl Automating Updates on Ubuntu and Debian Scheduling Bash Scripts with cron Using Lock Files to Prevent Duplicate Runs Building a Simple Health-Check Script Sending Notifications from Bash Scripts Using Bash in Git Workflows Bash Scripts for Docker Automation Automating Docker Container Health Checks Using Bash in CI/CD Pipelines Environment Configuration for Deployment Scripts Automating SSH Tasks with Bash Deploying a Web Application with a Bash Script Using Bash to Process Application Logs Building Repeatable Development Setup Scripts Bash Debugging Techniques Using set -x and PS4 for Debug Traces Testing Bash Scripts with Bats Mocking Commands During Script Tests Testing Error Paths and Exit Codes Writing Portable Shell Scripts Bash-Specific Syntax vs. POSIX Shell Syntax Using ShellCheck in a Development Workflow Performance Tips for Bash Scripts Build an Interactive Calculator Build a File and Directory Organizer Build a Timestamped Backup Script Build a Log File Analyzer Build a Bulk File Renaming Tool Build a System Resource Monitoring Script Build a Website Uptime Checker Build a User Account Audit Report Build a Database Backup Automation Script Build a Docker Cleanup Helper Build a Server Health-Check and Alert Script Build a Deployment Automation Script Build a Menu-Driven Linux Administration Toolkit Build a Safe Automated Backup and Restore Workflow
Ask about this post
AI Ask about this post

Ask questions about Looping Through Files and Directories and get answers drawn from it.

Signed-in readers only.