Published on

Efficiently Organizing Your Screenshots with a Bash Script

Authors

Recently, I've got a Synology NAS to organize all my files in a single place.

To my surprise, I've more than 5000 screenshots that I've taken across devices since 2014.

And organising all those files in one go doesn't seem possible.

So what I did is wrote a bash script (with the help of ChatGPT for CLI syntax) that will sorts them based on the year and month they were taken.

This way, we can easily access your screenshots by navigating to the appropriate year and month directories.

How it works?

  1. We'll be using stat command to get the creation date of each screenshot
  2. mkdir command to create a new directory for the year and month if it doesn't already exist.
  3. mv command to move the screenshot into the appropriate directory.

Snippet

Here's an example of a bash script that does this:

#!/bin/bash

# Set the starting directory (that you're currently in)
start_dir=$(pwd)

# Loop through all files in the starting directory
for file in "$start_dir"/*
do
    # Get the year and month that the file was created
    year=$(stat -f "%Sm" -t "%Y" "$file")
    month=$(stat -f "%Sm" -t "%m" "$file")
    
    # Check if a directory for the year & month already exists
    if [ ! -d "$start_dir/$year/$month" ]
    then
        # Create a new directory for the month if it doesn't exist
        mkdir -p "$start_dir/$year/$month"
    fi
    
    # Check if the file is a regular file (not a directory)
    if [ -f "$file" ]
    then
      # Move the file to the directory for the year and month it was created
      mv "$file" "$start_dir/$year/$month"
    fi
done

To use this script, save it as a file (e.g. organize_screenshots.sh) and make it executable using the chmod command:

chmod +x organize_screenshots.sh

Then navigate to the directory that contains your screenshots and run the script:

./organize_screenshots.sh

This will organize all your screenshots in the current directory into subdirectories based on the year and month they were taken.

With a bash script like this, organizing your screenshots becomes a breeze. No more sifting through a cluttered folder - just navigate to the appropriate year and month directories to find the screenshot you need.

Happy organizing!

Here's is how my current screenshots directories looks like 🔥