🛠 Project: Tidy the Downloads Folder
Everyone's Downloads folder ends up like ~/downloads: PDFs, photos, music and zips, all in one pile. Sorting it by hand takes ages. A script does it in a second, and works just as well next month.
What the script has to do
~/scripts/organize.sh FOLDER (and without a folder: ~/downloads):
- Move each file into a folder named after its type:
report.pdf→pdf/report.pdf,beach.jpg→jpg/beach.jpg - Handle names with spaces (
holiday photo.jpg) - Put files without an extension (
README) intoother/ - Leave folders alone (
old/stays as it is) - With
-nfirst, only print what it would move, and move nothing (a "dry run")
Building blocks
for f in ~/downloads/*; do echo "$f"; done # Every file, one at a time
f="holiday photo.jpg"; echo "${f##*.}" # jpg: everything after the last dot
[ -f "$f" ] || continue # Skip what isn't a file (folders)
[[ "$f" == *.* ]] # True when the name has a dot
mkdir -p jpg && mv "$f" jpg/ # Quotes keep "holiday photo.jpg" one name
DIR=${1:-~/downloads} # The first argument, or ~/downloads
if [ "$1" = "-n" ]; then DRY=1; shift; fi # shift: drop $1, the folder becomes $1
💡 Always quote
"$f": without the quotes,holiday photo.jpgbecomes two names,holidayandphoto.jpg. Try the dry run first. That's what admins do before a script moves or deletes anything.