Beginner · 20 min · practise every command in the built-in terminal

🛠 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):

  1. Move each file into a folder named after its type: report.pdf → pdf/report.pdf, beach.jpg → jpg/beach.jpg
  2. Handle names with spaces (holiday photo.jpg)
  3. Put files without an extension (README) into other/
  4. Leave folders alone (old/ stays as it is)
  5. With -n first, 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.jpg becomes two names, holiday and photo.jpg. Try the dry run first. That's what admins do before a script moves or deletes anything.

Practice tasks

  1. Create ~/scripts/organize.sh, a bash script, and make it executable
  2. Dry run: with -n it prints what it would move, and moves nothing
  3. Run it for real: every file is in a folder named after its type
  4. The names with spaces made it too
  5. README is in other/, and the old/ folder wasn't touched

Commands in this lesson

Projects