Project: Photo Renamer
Tidy names, automatically.
Cameras give photos names like IMG_four four one seven. After a holiday, you'd like names like Spain zero zero one, Spain zero zero two. Let's write a script that does it for a whole folder.

- Camera names: IMG_4417.jpg
- We want: spain-001.jpg
- One script, a whole folder
rename.sh
The script takes two arguments, the folder, and the new name. A for loop visits each JPG. Print F, percent zero three D, turns the counter into three digits, like zero zero one. Echo shows each change, and MV does the renaming. Then the counter goes up by one.
#!/bin/bash
# Rename every photo to name-001.jpg, name-002.jpg ...
folder="$1"
name="$2"
n=1
for f in "$folder"/*.jpg; do
new="$folder/$name-$(printf %03d $n).jpg"
echo "$f -> $new"
mv "$f" "$new"
n=$((n + 1))
doneRunning the project
Here's the folder before, full of camera names. We run the script on holiday, with the name spain. Each photo is renamed, and listed as it goes. LS shows the tidy result.
ls holiday IMG_4417.jpg IMG_4418.jpg IMG_4421.jpg IMG_4502.jpg IMG_4503.jpg ./rename.sh holiday spain holiday/IMG_4417.jpg -> holiday/spain-001.jpg holiday/IMG_4418.jpg -> holiday/spain-002.jpg holiday/IMG_4421.jpg -> holiday/spain-003.jpg holiday/IMG_4502.jpg -> holiday/spain-004.jpg holiday/IMG_4503.jpg -> holiday/spain-005.jpg ls holiday spain-001.jpg spain-002.jpg spain-003.jpg spain-004.jpg spain-005.jpg
Test before you trust
Renaming files can't be undone easily. So a good habit is a dry run. Put echo in front of the MV the first time, so the script only prints what it would do. When you're happy, remove the echo, and run it for real.
| key | value |
|---|---|
| printf %03d | 001, 002, 003 |
| "$folder"/*.jpg | every photo |
| echo mv … | a dry run first |
| Then mv | do it for real |
Summary
Our renamer loops over the photos, builds a tidy name with print F, and moves each file. Always try a dry run first. Next, a project that reports on a log file.
Key takeaways- for f in dir/*.jpg
- printf %03d
- Dry run with echo