Menu
Coddy logo textTech

File Organizer By Type

Part of the Fundamentals section of Coddy's Terminal journey — lesson 80 of 82.

challenge icon

Challenge

Easy

Create a shell script called organize.sh that organizes files in the downloads folder by moving them into subfolders based on their file extensions.

Your script should:

  1. Start with the shebang line (#!/bin/bash)
  2. Loop through all files in the downloads directory
  3. For each file, extract its extension using ${file##*.}
  4. Create a folder for that extension inside downloads if it doesn't exist
  5. Move the file into its corresponding extension folder
  6. Print Moved [filename] to [extension]/ for each file moved

Make the script executable and run it. Your output should be:

Moved document.pdf to pdf/
Moved image.jpg to jpg/
Moved notes.txt to txt/
Moved photo.jpg to jpg/
Moved readme.txt to txt/
Moved report.pdf to pdf/
Moved song.mp3 to mp3/
Moved track.mp3 to mp3/

After running the script, verify the organization by listing the downloads folder with ls downloads. You should see four folders: jpg, mp3, pdf, and txt.

Hint: Use for file in downloads/*; do to loop through files. Inside the loop, extract just the filename with basename "$file" and the extension with ${file##*.}. Use mkdir -p "downloads/$ext" to create the folder and mv "$file" "downloads/$ext/" to move the file.

Try it yourself

Terminal

All lessons in Fundamentals