Menu
CoddyTech

Batch Renamer

Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 37 of 39.

challenge icon

Challenge

Hard

Write rename.sh, which renames every .jpeg file in a folder to .jpg without overwriting anything.

  1. The script takes one argument, the folder. With any other number of arguments, print Usage: rename.sh DIR to stderr and exit 1.
  2. When the argument is not a folder, print Error: DIR is not a folder to stderr, with the argument in place of DIR, and exit 2.
  3. Go through the files ending in .jpeg directly inside the folder, in alphabetical order. For each one, the new name ends in .jpg instead.
  4. When a file with the new name already exists, leave both files as they are and print Skipped OLD: NEW exists. Otherwise rename the file and print OLD -> NEW. Print names without the folder.
  5. Last, print Renamed: R, skipped: S with the two counts, and exit 0. A folder without .jpeg files prints Renamed: 0, skipped: 0.
  6. File names may contain spaces.

Try it: photos holds beach.jpeg, city.jpeg, city.jpg, notes.txt and park.jpeg. Run bash rename.sh photos. It prints:

beach.jpeg -> beach.jpg
Skipped city.jpeg: city.jpg exists
park.jpeg -> park.jpg
Renamed: 2, skipped: 1

Then ls photos lists beach.jpg, city.jpeg, city.jpg, notes.txt and park.jpg. A path that is not a folder fails:

bash rename.sh pics 2>&1; echo "exit $?"
Error: pics is not a folder
exit 2

Try it yourself

Terminal

All lessons in Bash Scripting

Practice on your own: Terminal playground