Looping Through Files and Directories
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.txtas 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.txtwas 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
Clocale that means uppercase letters come before lowercase letters, soB.txtis listed beforea.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.
Symbolic Links
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).