Bash Project: File Organizer
A file organizer script sorts loose files into folders by extension. This project combines globs, a loop, and a case statement in one useful script.
Create folders safely
The mkdir -p command creates a folder. Running it a second time stays quiet, because the folder already exists.
mkdir -p txt
mkdir -p txt
touch txt/note.txt
ls txtMove files by extension
A case statement checks each file name. Text files move into txt, and images move into jpg.
mkdir -p txt jpg
touch song.txt photo.jpg
for file in *.txt *.jpg; do
case "$file" in
*.txt) mv "$file" txt ;;
*.jpg) mv "$file" jpg ;;
esac
done
ls txt
ls jpgExample
touch a.txt b.txt a.jpg notes.md todo
mkdir -p txt jpg md
for file in *; do
case "$file" in
*.txt) mv "$file" txt ;;
*.jpg) mv "$file" jpg ;;
*.md) mv "$file" md ;;
esac
done
echo "txt folder:"
ls txt
echo "jpg folder:"
ls jpg
echo "md folder:"
ls md
echo "Counts:"
echo "txt: $(ls txt | wc -l)"
echo "jpg: $(ls jpg | wc -l)"
echo "md: $(ls md | wc -l)"
if [ -f todo ]; then
echo "todo stayed loose"
fiKey points
- The mkdir -p command creates folders and stays quiet if they exist.
- A glob like * lists every name in the current folder.
- A case statement can match a file name against extension patterns.
- The mv command moves a matched file into its folder.
- A file with no matching extension stays where it is.
- Listing each folder after the moves proves the sort worked.
In this example, the loop visits every name in the folder, and the case statement moves each file by its extension. The listings and counts prove where every file landed. The file todo has no extension, so it stays loose.
Try it Yourself
Edit the code, then press Run.
Running is simulated
Exercise
What does mkdir -p txt do when the folder txt already exists?