Build a File and Directory Organizer
This project builds organize.sh, a script that tidies a cluttered folder such as ~/Downloads. It looks at every file directly inside the folder and moves it into a subfolder: Images, Documents, Audio, Archives and so on by file type, or 2026/11, 2026/12 by modification date. It has a dry-run mode that shows the plan without touching anything, it never overwrites a file, it handles any file name Linux allows (spaces, tabs, newlines, leading dashes), and it writes a log of every move so a single command can undo the whole run.
Moving files around is easy. Moving them around safely, in a way you would trust on a folder full of real documents, is the actual subject of this project. It brings together several earlier lessons: getopts (lesson 130), associative arrays (lesson 102), parameter expansion (lessons 54 and 152), find -print0 and NUL-separated data (lesson 112), process substitution (lesson 151), and safe handling of destructive commands (lesson 160).
What the Organizer Should Do
Writing the requirements first keeps the design focused:
- Sort by type using the file extension, case-insensitively:
photo.JPGandlogo.pngboth go toImages. - Sort by date with
-d, intoYEAR/MONTHfolders based on each file's modification time. - Dry run with
-n: print what would happen and change nothing. - Never overwrite. If
Images/logo.pngalready exists, the incoming file becomesImages/logo (1).png. - Undo with
-u: put every file back where it was and remove folders that became empty. - Leave alone hidden files (
.bashrc,.git), subdirectories and anything that is not a regular file. - Handle every legal file name, including names with spaces, newlines or a leading
-. - Report clearly: a per-folder count, and an exit status that tells a calling script whether every file was moved.
Design Decisions
Only the Top Level of the Folder
The organizer processes files directly inside the target directory (find -mindepth 1 -maxdepth 1). It does not descend into subdirectories. This matters for two reasons. First, a project folder inside Downloads should stay intact; pulling its main.py into a Code folder would break it. Second, after the first run the category folders themselves are subdirectories, so running the script again finds nothing new to move instead of shuffling already sorted files. The script is therefore idempotent: running it twice has the same effect as running it once.
Mapping Extensions to Folders
An associative array is the natural data structure for "extension → folder". Typing [jpg]=Images [jpeg]=Images [png]=Images ... for fifty extensions is tedious and error-prone, so a small helper fills the array one category at a time:
declare -A CATEGORY=()
add_category() { # add_category FOLDER EXT...
local folder=$1 ext
shift
for ext in "$@"; do CATEGORY[$ext]=$folder; done
}
add_category Images jpg jpeg png gif webp svg bmp tiff heic
add_category Documents pdf doc docx odt rtf txt md epub
shift removes the folder name from the argument list, so "$@" then holds only the extensions. Adding a new category later is one line.
Looking up a file's folder uses two parameter expansions:
category_for() {
local name=$1 ext
if [[ $name != *.* ]]; then # no extension at all
echo Other
return
fi
ext=${name##*.}
ext=${ext,,} # PDF and pdf are the same type
echo "${CATEGORY[$ext]:-Other}"
}
${name##*.}removes the longest prefix matching*., leaving everything after the last dot:report.final.docxgivesdocx, andbackup.tar.gzgivesgz, which is listed underArchives.${ext,,}converts the extension to lowercase (Bash 4 and later), soJPGmatches thejpgkey.${CATEGORY[$ext]:-Other}returns the folder, orOtherwhen the extension is not in the table. Files without any dot, likeREADMEorLICENSE, also go toOther.
Not Overwriting Anything
A plain mv source target silently replaces target if it exists. In an organizer that would destroy data the first time two files share a name. The script protects against this at two levels.
The first level picks a free name before moving. unique_path returns the destination path unchanged when it is free, and otherwise inserts (1), (2) and so on before the extension, the way most file managers do:
unique_path() {
local dir=$1 name=$2 base ext="" n=1 candidate
candidate=$dir/$name
[[ ! -e $candidate ]] && { printf '%s\n' "$candidate"; return; }
base=$name
if [[ $name == ?*.* ]]; then # split "report.final.pdf" into "report.final" + ".pdf"
base=${name%.*}
ext=.${name##*.}
fi
while [[ -e "$dir/$base ($n)$ext" ]]; do
n=$((n + 1))
done
printf '%s\n' "$dir/$base ($n)$ext"
}
${name%.*} removes the shortest suffix starting with a dot, so only the last extension is split off. The pattern ?*.* requires at least one character before the dot; a name like .profile would otherwise be split into an empty base and the "extension" .profile.
The second level is the move itself. Between the moment unique_path checks a name and the moment mv runs, another program could create a file with that name. mv -n ("no clobber") refuses to replace an existing target. Because the exact exit status of a skipped mv -n has changed between GNU coreutils releases, the script does not rely on it alone; it also checks that the source file is really gone:
if mv -n -- "$file" "$target" 2>/dev/null && [[ ! -e $file ]]; then
The -- marks the end of options, so a file called -rf.txt is treated as a file name and not as options to mv.
Reading File Names Safely
File names on Linux may contain any byte except / and NUL, including spaces and newlines. A loop like for f in $(ls) splits names on whitespace and breaks on all of these. The organizer uses the safe pattern from lesson 112: find prints each name followed by a NUL byte, and read -d '' reads up to the next NUL:
while IFS= read -r -d '' file; do
...
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type f ! -name '.*' -print0 | sort -z)
-type fselects regular files only; directories, symbolic links and device files are left in place.! -name '.*'skips hidden files.sort -zsorts NUL-separated records, so the output is in a predictable order.< <( ... )is process substitution. It feeds the loop without a pipe, so the loop runs in the current shell and the counters it updates (moved,failed,count) are still set after the loop ends. Withfind ... | while read, the loop would run in a subshell and all its counts would be lost.
An Undo Log That Survives Any File Name
To undo a run, the script must remember each pair of "original path" and "new path". A text log with one pair per line would break on file names containing a newline or a tab. The log therefore uses the same NUL separation as find -print0: each move appends two NUL-terminated records:
printf '%s\0%s\0' "$file" "$target" >> "$log"
The undo function reads the records back two at a time:
while IFS= read -r -d '' src && IFS= read -r -d '' dest; do
...
done < "$log"
The log lives inside the organized directory as a hidden file, .organize-20261202-170402-117629212.log. The time stamp includes nanoseconds (%N, a GNU date feature) so that two runs in the same second get different names, and the file is created with noclobber set (set -o noclobber; : > "$log") so an existing log is never truncated. Because the name starts with a dot, the organizer never tries to sort its own log into Other.
Undo handles four situations for each recorded move:
| Situation | Action |
|---|---|
| The original path is free and the moved file exists | Move it back and remove its folder if it is now empty |
| The original path exists and the moved file does not | Already restored by an earlier undo: skip silently |
| Both exist | A new file took the old name: report it and leave the moved file in place |
| Neither exists | The file was deleted or moved since: report it |
The log is deleted only when every file was restored. If anything was left behind, the log is kept, so the user can resolve the conflict and run -u again; the second run skips the files that are already back.
Choosing Not to Use set -e for Every Failure
The script starts with set -euo pipefail (lesson 121), which turns unexpected errors into an immediate exit. Expected failures, such as one file that cannot be moved, are handled explicitly instead: the loop prints a message, increments failed and continues with the next file. Stopping halfway through a folder because one file is locked would leave the user with a half-organized directory and no summary. At the end, (( failed == 0 )) becomes the function's return status, and therefore the script's exit status.
The Complete Script
#!/usr/bin/env bash
#
# organize.sh - sort the files in a directory into subfolders
#
# Usage: organize.sh [-n] [-d] DIRECTORY organize (by type, or by date with -d)
# organize.sh -u DIRECTORY undo the most recent run
#
# Options:
# -n dry run: show what would happen, change nothing
# -d sort into YEAR/MONTH folders by modification time instead of by type
# -u undo the most recent run in DIRECTORY
# -h show this help
#
# Only regular, non-hidden files directly inside DIRECTORY are moved.
# Existing files are never overwritten: a clash gets a " (1)", " (2)" ... suffix.
# Every move is recorded in DIRECTORY/.organize-TIMESTAMP.log so it can be undone.
#
# Exit status: 0 success, 1 some files could not be moved, 2 usage error.
set -euo pipefail
readonly PROG=${0##*/}
declare -A CATEGORY=()
add_category() { # add_category FOLDER EXT...
local folder=$1 ext
shift
for ext in "$@"; do CATEGORY[$ext]=$folder; done
}
add_category Images jpg jpeg png gif webp svg bmp tiff heic
add_category Documents pdf doc docx odt rtf txt md epub
add_category Spreadsheets xls xlsx ods csv tsv
add_category Presentations ppt pptx odp key
add_category Audio mp3 wav flac ogg m4a aac
add_category Video mp4 mkv mov avi webm wmv
add_category Archives zip tar gz tgz bz2 xz 7z rar
add_category Code sh py js ts html css c h cpp java go rs json yaml yml sql
add_category Installers deb rpm dmg exe msi appimage iso
usage() {
sed -n '3,17s/^# \{0,1\}//p' "$0"
}
die() {
printf '%s: %s\n' "$PROG" "$1" >&2
exit "${2:-1}"
}
# category_for NAME - print the folder for a file name, based on its extension
category_for() {
local name=$1 ext
if [[ $name != *.* ]]; then # no extension at all
echo Other
return
fi
ext=${name##*.}
ext=${ext,,} # PDF and pdf are the same type
echo "${CATEGORY[$ext]:-Other}"
}
# date_folder FILE - print YEAR/MONTH of the file's modification time
date_folder() {
date -r "$1" +%Y/%m
}
# unique_path DIR NAME - print DIR/NAME, or DIR/NAME (N).ext if that already exists
unique_path() {
local dir=$1 name=$2 base ext="" n=1 candidate
candidate=$dir/$name
[[ ! -e $candidate ]] && { printf '%s\n' "$candidate"; return; }
base=$name
if [[ $name == ?*.* ]]; then # split "report.final.pdf" into "report.final" + ".pdf"
base=${name%.*}
ext=.${name##*.}
fi
while [[ -e "$dir/$base ($n)$ext" ]]; do
n=$((n + 1))
done
printf '%s\n' "$dir/$base ($n)$ext"
}
# organize DIRECTORY BY_DATE DRY_RUN
organize() {
local dir=$1 by_date=$2 dry_run=$3
local file name folder target log="" moved=0 failed=0
declare -A count=()
if (( ! dry_run )); then
log=$dir/.organize-$(date +%Y%m%d-%H%M%S-%N).log
( set -o noclobber; : > "$log" ) || die "cannot create log file $log"
fi
while IFS= read -r -d '' file; do
name=${file##*/}
if (( by_date )); then
folder=$(date_folder "$file")
else
folder=$(category_for "$name")
fi
if (( dry_run )); then
printf 'would move %-30s -> %s/\n' "$name" "$folder"
count[$folder]=$(( ${count[$folder]:-0} + 1 ))
continue
fi
mkdir -p -- "$dir/$folder"
target=$(unique_path "$dir/$folder" "$name")
if mv -n -- "$file" "$target" 2>/dev/null && [[ ! -e $file ]]; then
printf '%s\0%s\0' "$file" "$target" >> "$log"
count[$folder]=$(( ${count[$folder]:-0} + 1 ))
moved=$((moved + 1))
[[ $target != "$dir/$folder/$name" ]] && printf 'renamed %s -> %s\n' "$name" "${target##*/}"
else
printf '%s: could not move %s\n' "$PROG" "$name" >&2
failed=$((failed + 1))
fi
done < <(find "$dir" -mindepth 1 -maxdepth 1 -type f ! -name '.*' -print0 | sort -z)
if (( ${#count[@]} == 0 )); then
echo "nothing to organize in $dir"
[[ -n $log ]] && rm -f -- "$log"
return 0
fi
printf '%s\n' "${!count[@]}" | sort | while IFS= read -r folder; do
printf ' %-14s %3d file(s)\n' "$folder" "${count[$folder]}"
done
if (( dry_run )); then
echo "dry run: nothing was moved"
else
printf 'moved %d file(s); undo with: %s -u %q\n' "$moved" "$PROG" "$dir"
fi
(( failed == 0 ))
}
# undo DIRECTORY - move the files of the most recent run back
undo() {
local dir=$1 log src dest restored=0 failed=0 folder
log=$(find "$dir" -maxdepth 1 -type f -name '.organize-*.log' | sort | tail -n 1)
[[ -n $log ]] || die "no organize log found in $dir"
while IFS= read -r -d '' src && IFS= read -r -d '' dest; do
if [[ -e $src && ! -e $dest ]]; then # restored by an earlier undo
continue
elif [[ -e $src ]]; then
printf '%s: %s already exists, left %s in place\n' "$PROG" "${src##*/}" "$dest" >&2
failed=$((failed + 1))
elif [[ ! -e $dest ]]; then
printf '%s: %s has disappeared\n' "$PROG" "$dest" >&2
failed=$((failed + 1))
elif mv -n -- "$dest" "$src" 2>/dev/null; then
restored=$((restored + 1))
folder=${dest%/*}
# remove the folder once it is empty, and the YEAR folder above it in date mode
rmdir -- "$folder" 2>/dev/null || true
if [[ ${folder%/*} != "$dir" ]]; then
rmdir -- "${folder%/*}" 2>/dev/null || true
fi
else
printf '%s: could not restore %s\n' "$PROG" "$dest" >&2
failed=$((failed + 1))
fi
done < "$log"
echo "restored $restored file(s) from ${log##*/}"
if (( failed == 0 )); then
rm -f -- "$log"
else
echo "kept ${log##*/} because $failed file(s) could not be restored" >&2
return 1
fi
}
# --- main ----------------------------------------------------------------------
by_date=0 dry_run=0 undo_mode=0
while getopts ':ndhu' opt; do
case $opt in
n) dry_run=1 ;;
d) by_date=1 ;;
u) undo_mode=1 ;;
h) usage; exit 0 ;;
*) die "unknown option -$OPTARG (try -h)" 2 ;;
esac
done
shift $((OPTIND - 1))
(( $# == 1 )) || die "expected exactly one directory (try -h)" 2
target_dir=${1%/}
[[ -n $target_dir ]] || target_dir=/
[[ -d $target_dir ]] || die "not a directory: $1" 2
[[ -w $target_dir ]] || die "no write permission for: $1" 2
if (( undo_mode )); then
undo "$target_dir"
else
organize "$target_dir" "$by_date" "$dry_run"
fi
A few lines deserve a closer look:
usageprints the header comment.sed -n '3,17s/^# 0 0,1 1 //p' "$0"reads the script's own lines 3 to 17 and removes the leading#. The help text and the documentation at the top of the file can never drift apart, because they are the same text.target_dir=${1%/}removes one trailing slash, soDownloads/andDownloadsproduce the same paths in messages and in the log. The following line turns an empty result (the user passed/) back into/.- The write-permission check (
[[ -w $target_dir ]]) stops early with a clear message instead of failing on every file. - The summary is printed by piping the folder names through
sort. The loop after the pipe runs in a subshell, but it only readscount, so that does not matter here. printf %qin the final message quotes the directory name, so the suggested undo command can be copied and pasted even when the name contains spaces.rmdironly removes empty directories, which makes it the safe way to clean up after undo. A category folder that still contains other files, such as anImagesfolder that existed before the run, is left alone. In date mode, the year folder is removed as well once its last month folder is gone.
Running the Organizer
Preparing a Test Folder
Never test a file-moving script on real data first. Build a disposable folder with the kinds of names that cause trouble:
mkdir -p demo/Downloads && cd demo
touch Downloads/{"holiday photo.JPG",logo.png,invoice-2026.pdf,notes.txt,report.final.docx} \
Downloads/{budget.xlsx,data.csv,song.mp3,clip.mp4,backup.tar.gz,setup.sh,README,LICENSE,.hidden}
mkdir Downloads/Images && touch Downloads/Images/logo.png # a name clash waiting to happen
touch -d '2025-03-14' Downloads/invoice-2026.pdf # an older file, for date mode
Dry Run
$ ./organize.sh -n Downloads
would move LICENSE -> Other/
would move README -> Other/
would move backup.tar.gz -> Archives/
would move budget.xlsx -> Spreadsheets/
would move clip.mp4 -> Video/
would move data.csv -> Spreadsheets/
would move holiday photo.JPG -> Images/
would move invoice-2026.pdf -> Documents/
would move logo.png -> Images/
would move notes.txt -> Documents/
would move report.final.docx -> Documents/
would move setup.sh -> Code/
would move song.mp3 -> Audio/
Archives 1 file(s)
Audio 1 file(s)
Code 1 file(s)
Documents 3 file(s)
Images 2 file(s)
Other 2 file(s)
Spreadsheets 2 file(s)
Video 1 file(s)
dry run: nothing was moved
sort -z orders the names by byte value in the C locale and by the locale's collation rules otherwise, so the exact order of the list may differ on your system. .hidden and the existing Images folder are not listed, and holiday photo.JPG is recognized as an image despite the uppercase extension.
Organizing by Type
$ ./organize.sh Downloads
renamed logo.png -> logo (1).png
Archives 1 file(s)
Audio 1 file(s)
Code 1 file(s)
Documents 3 file(s)
Images 2 file(s)
Other 2 file(s)
Spreadsheets 2 file(s)
Video 1 file(s)
moved 13 file(s); undo with: organize.sh -u Downloads
$ find Downloads -type f | sort
Downloads/.hidden
Downloads/.organize-20261202-170402-117629212.log
Downloads/Archives/backup.tar.gz
Downloads/Audio/song.mp3
Downloads/Code/setup.sh
Downloads/Documents/invoice-2026.pdf
Downloads/Documents/notes.txt
Downloads/Documents/report.final.docx
Downloads/Images/holiday photo.JPG
Downloads/Images/logo (1).png
Downloads/Images/logo.png
Downloads/Other/LICENSE
Downloads/Other/README
Downloads/Spreadsheets/budget.xlsx
Downloads/Spreadsheets/data.csv
Downloads/Video/clip.mp4
The clash was resolved without loss: the logo.png that was already in Images is untouched, and the incoming one became logo (1).png. Running the script a second time changes nothing:
$ ./organize.sh Downloads
nothing to organize in Downloads
The log contains the pairs of paths. tr '\0' '\n' makes it readable for a quick look (for names without newlines):
$ tr '\0' '\n' < Downloads/.organize-*.log | head -4
Downloads/LICENSE
Downloads/Other/LICENSE
Downloads/README
Downloads/Other/README
Undoing a Run
$ ./organize.sh -u Downloads
restored 13 file(s) from .organize-20261202-170402-117629212.log
$ ls -A Downloads
.hidden Images LICENSE README backup.tar.gz budget.xlsx clip.mp4 data.csv
holiday photo.JPG invoice-2026.pdf logo.png notes.txt report.final.docx setup.sh song.mp3
All the category folders are gone except Images, which still holds the logo.png that was there before the run.
Organizing by Date
$ ./organize.sh -d Downloads
2025/03 1 file(s)
2026/12 12 file(s)
moved 13 file(s); undo with: organize.sh -u Downloads
$ find Downloads/2025
Downloads/2025
Downloads/2025/03
Downloads/2025/03/invoice-2026.pdf
The date comes from date -r FILE +%Y/%m, which prints the modification time of FILE in the given format. invoice-2026.pdf was back-dated with touch -d, so it lands in 2025/03; the others were created today. Undo removes both the month folders and the empty year folders.
When Undo Meets a Conflict
Suppose that after organizing, a new notes.txt is downloaded into the folder. Undo cannot put the old notes.txt back without overwriting the new one, so it leaves it where it is:
$ ./organize.sh Downloads > /dev/null
$ touch Downloads/notes.txt
$ ./organize.sh -u Downloads; echo "status $?"
organize.sh: notes.txt already exists, left Downloads/Documents/notes.txt in place
restored 12 file(s) from .organize-20261202-170531-480127733.log
kept .organize-20261202-170531-480127733.log because 1 file(s) could not be restored
status 1
After renaming the new file, a second undo finishes the job. The twelve files that are already back are skipped silently:
$ mv Downloads/notes.txt Downloads/notes-new.txt
$ ./organize.sh -u Downloads; echo "status $?"
restored 1 file(s) from .organize-20261202-170531-480127733.log
status 0
Difficult File Names
Names with a leading dash, a tab or even a newline go through the organizer and back unchanged. cat -A shows the tab as ^I and marks each line end with $:
$ mkdir t && touch t/-rf.txt $'t/line\nbreak.pdf' $'t/tab\tname.mp3'
$ ./organize.sh t > /dev/null
$ find t -type f ! -name '.*' | cat -A
t/Documents/-rf.txt$
t/Documents/line$
break.pdf$
t/Audio/tab^Iname.mp3$
$ ./organize.sh -u t
restored 3 file(s) from .organize-20261202-170406-728053053.log
$'...' is ANSI-C quoting, which turns \n and \t into a real newline and tab inside the name.
Error Handling
$ ./organize.sh nowhere; echo "status $?"
organize.sh: not a directory: nowhere
status 2
$ ./organize.sh -x Downloads; echo "status $?"
organize.sh: unknown option -x (try -h)
status 2
$ ./organize.sh; echo "status $?"
organize.sh: expected exactly one directory (try -h)
status 2
$ ./organize.sh -u Downloads; echo "status $?"
organize.sh: no organize log found in Downloads
status 1
The exit codes follow the convention from lesson 116: 2 for incorrect usage, 1 for an operation that failed.
Using the Organizer Automatically
Because the script is idempotent and logs every move, it is safe to run on a schedule. A crontab entry (lesson 170) that tidies the Downloads folder every evening at 21:30 and keeps a record of what happened:
30 21 * * * $HOME/bin/organize.sh "$HOME/Downloads" >> "$HOME/.local/state/organize.log" 2>&1
cron runs commands with a minimal environment, so the script is called by its full path. Each run creates a new undo log in the Downloads folder; -u always undoes the most recent one, so a run can be reverted the next morning if something was moved that should not have been.
Portability Notes
The script targets Bash 4 or later (for associative arrays and ${ext,,}) and GNU tools:
date -r FILEprints a file's modification time with GNUdate. On macOS, the equivalent isstat -f %Sm -t %Y/%m FILE.date +%N(nanoseconds) is a GNU extension; BSDdateprints a literalN.sort -zandfind -print0are available in GNU and BSD versions.- macOS ships Bash 3.2, which has no associative arrays. Installing a current Bash (for example with Homebrew) solves this, as described in lesson 8.
Ideas for Extending the Project
- A configuration file. Read extra
add_categorylines from~/.config/organize.conf, so users can add their own types (for exampleadd_category Fonts ttf otf woff2) without editing the script. Validate each line instead of sourcing the file blindly (lesson 157). - Content-based detection. Files without an extension could be classified with
file --mime-type -b FILE, which inspects the content:image/pnggoes toImages,application/pdftoDocuments. - Duplicate detection. Before renaming a clash to
logo (1).png, compare both files withcmp -s; if they are identical, the incoming copy could be moved to aDuplicatesfolder instead. - A minimum age. Add an option such as
-a 2that only moves files older than two days (find -mtime +1), so a download that is still in progress is never moved. - Tests. The dry-run output and the exit codes make the script easy to cover with Bats (lessons 185 and 187): create a temporary folder in
setup, run the organizer, and assert on the resulting tree and on undo.