Batch Renamer
Part of the Bash Scripting section of Coddy's Terminal journey. Lesson 37 of 39.
Challenge
HardWrite rename.sh, which renames every .jpeg file in a folder to .jpg without overwriting anything.
- The script takes one argument, the folder. With any other number of arguments, print
Usage: rename.sh DIRto stderr and exit1. - When the argument is not a folder, print
Error: DIR is not a folderto stderr, with the argument in place of DIR, and exit2. - Go through the files ending in
.jpegdirectly inside the folder, in alphabetical order. For each one, the new name ends in.jpginstead. - 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 printOLD -> NEW. Print names without the folder. - Last, print
Renamed: R, skipped: Swith the two counts, and exit0. A folder without.jpegfiles printsRenamed: 0, skipped: 0. - 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: 1Then 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 2Try it yourself
All lessons in Bash Scripting
1Arguments And Exit Codes
Script ArgumentsAll The ArgumentsExit CodesChecking ArgumentsRecap - Unit ConverterPractice on your own: Terminal playground