$_ CLI In Depth
Learning progress 0%
build expansion quoting word-splitting

Build: A Safe Batch File Renamer

4 min read Module 8: Expansion, Quoting & Word Splitting Updated Dec 5, 2026
Cheat Sheet
0:00 / 3:12

The specification

The script is called rename-batch.sh. It takes three arguments, an old text, a new text, and a directory, and it renames each entry directly inside that directory whose name contains the old text. Every occurrence of the old text in the name is replaced with the new text. The script does not descend into subdirectories, so it touches only the entries it was asked about.

It accepts one optional flag, --dry-run, placed before the arguments. With that flag, the script prints a line for each rename it would perform and changes nothing. Without the flag, it performs the renames. Both modes report the same set of planned changes, so a dry run is a reliable preview.

The script must never overwrite a file. If the target name already exists, it prints a skip message to standard error, does not move anything, and makes the final exit status 1. It must handle names with spaces, newlines, and leading dashes, and it must refuse an empty old text, because an empty pattern would match every name. A usage error exits with status 2, and so does a directory that does not exist.

Why the design looks the way it does

The directory is read with find and -print0, and each record is read with read -r -d '', so no name is ever split. The old text is matched with case, using the quoted variable as a literal pattern, so characters such as an asterisk in the old text do not behave as wildcards. The replacement uses the parameter operator with doubled slashes and a quoted pattern, which also treats the old text literally.

Every move uses the end-of-options marker and quoted names. Before each move, the script tests whether the target exists, because mv would silently overwrite it. A dry run performs the same tests, so the preview is honest about the skips too.

The reference solution

The following script is one correct way to meet the specification. It is short on purpose, so that each line can be checked against a requirement. Read it once in full, then run it on a copy of a directory before you trust it with real files.

BASH23 lines
#!/usr/bin/env bash
set -u
dry=0
if [ "${1:-}" = "--dry-run" ]; then dry=1; shift; fi
if [ $# -ne 3 ] || [ -z "$1" ]; then
  echo "usage: $0 [--dry-run] OLD NEW DIR" >&2; exit 2
fi
old=$1 new=$2 dir=$3
[ -d "$dir" ] || { echo "not a directory: $dir" >&2; exit 2; }
status=0
while IFS= read -r -d '' path; do
  name=${path##*/}
  case $name in *"$old"*) ;; *) continue ;; esac
  target=${path%/*}/${name//"$old"/"$new"}
  if [ -e "$target" ]; then
    echo "skip, exists: $target" >&2; status=1
  elif [ "$dry" -eq 1 ]; then
    printf 'would rename: %s -> %s\n' "$path" "$target"
  else
    mv -- "$path" "$target" || status=1
  fi
done < <(find "$dir" -mindepth 1 -maxdepth 1 -print0)
exit "$status"

Testing before trusting it

A renamer deserves a test plan. Create a scratch directory with a file that has a space, a file that begins with a dash, a file with a newline in its name, and an existing target that would be overwritten. Run the dry run first and compare its output with what you expect. Then run the real command and list the directory again. The skip message should appear for the collision, and the collision target should keep its original contents.

The script also has deliberate limits, and you should know them before you rely on it. It works only on the entries directly inside one directory, so a nested tree needs a different loop. It does not undo anything, so the dry run is the only preview you get. It treats the old text as a literal, so it cannot apply a regular expression. And because the check and the move are separate steps, it is safe for one user working on a quiet directory, but not for a directory that another program is writing to at the same time. Writing those limits down in a comment at the top of a script is a good habit, because the next reader will otherwise discover them the hard way. The labs in this lesson build the same logic in three stages: first a listing, then the moves, then the collision check. Each stage is small enough to verify on its own, and together they reproduce the behavior described in the specification. Keep the stages separate when you adapt the script for your own work, because a bug in one stage is far easier to find when the others are already known to be correct.

Terminal lab · 3 steps · real Linux in your browser

Build the renamer in stages

List planned renames NUL-safely, perform one rename with the end-of-options marker, and skip a collision without overwriting.

01
List matching names with a NUL-safe loop
The directory photos holds three entries, including one with a space. The loop reads each name whole, and the case statement keeps the names that contain the word draft. Run this in /workspace. ``bash cd /workspace/photos while IFS= read -r -d '' f; do case ${f##*/} in *draft*) printf '%s\n' "${f##*/}" ;; esac done < <(find . -mindepth 1 -maxdepth 1 -print0) > /workspace/plan.txt `` Run cat /workspace/plan.txt. It should list two names, one with a space and one with a dash.
Show hint for step 1
Loop over find -print0 records with read -r -d '', and print the name only when it contains draft. Write the names to /workspace/plan.txt.
02
Rename matches with mv and quoted names
A glob is safe for this job because each matching name arrives as one word. The end-of-options marker protects names that begin with a dash, and the quotes protect the space. Run this in /workspace. ``bash cd /workspace/photos for f in *draft*; do mv -- "$f" "${f//draft/done}"; done `` Run ls in the photos directory. You should see done one.txt and done-two.txt, and final.txt unchanged.
Show hint for step 2
Loop over the glob *draft* and use mv -- with quoted names. The replacement draft to done is a parameter operator.
03
Skip a rename when the target exists
The directory photos holds draft-x.txt and done-x.txt. Renaming the first to the second would overwrite the existing file, so the script must test first. This branch records the skip instead of moving the file. ``bash cd /workspace/photos if [ -e done-x.txt ]; then echo 'skip: done-x.txt exists' > /workspace/conflict.txt else mv -- draft-x.txt done-x.txt fi `` Run cat /workspace/conflict.txt. The draft file should still be there.
Show hint for step 3
Test for the target with -e before calling mv. Write the skip message to /workspace/conflict.txt when the target exists.
Check yourself Question 1 of 4
Concept Check Literal pattern in case recall

In case $name in *"$old"*) ..., why is "$old" quoted inside the pattern?

Recap & Key Takeaways

The script reads entries with find -print0 and read -r -d '', so no file name is split by spaces or newlines.
Every move uses mv -- with quoted names, and a test for an existing target prevents silent overwrites.
A dry run follows the same code path as the real run, so its preview includes the collisions that would be skipped.
Literal matching uses quoted patterns in case and in the replacement, so characters such as * in the old text are not wildcards.
Was this lesson helpful? Spot an issue or have a suggestion? Let us know on GitHub.
Report an issue