File Organizer By Type
Part of the Fundamentals section of Coddy's Terminal journey — lesson 80 of 82.
Challenge
EasyCreate 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:
- Start with the shebang line (
#!/bin/bash) - Loop through all files in the
downloadsdirectory - For each file, extract its extension using
${file##*.} - Create a folder for that extension inside
downloadsif it doesn't exist - Move the file into its corresponding extension folder
- 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/*; doto loop through files. Inside the loop, extract just the filename withbasename "$file"and the extension with${file##*.}. Usemkdir -p "downloads/$ext"to create the folder andmv "$file" "downloads/$ext/"to move the file.
Try it yourself
All lessons in Fundamentals
4Directories
Create A DirectoryCopy A DirectoryMove And Rename A DirectoryDelete A DirectoryRecap - Directory Operations7File Content
Head And TailWord CountSort CommandUnique CommandGrep BasicsGrep With FlagsRecap - Text Detective2Navigation
Print Working DirectoryList FilesChange DirectoryAbsolute vs Relative PathsHome And Root DirectoryRecap - Find Your Way8Redirection
Standard OutputOverwrite To A FileAppend To A FileStandard InputStandard ErrorRecap - Log Builder6Wildcards And Patterns
The Star WildcardThe Question Mark WildcardBracket WildcardsCombining WildcardsRecap - Selective Operations9Piping
What Is A PipeChaining Two CommandsChaining Multiple CommandsPipe With GrepRecap - Data Pipeline