March 15, 2017

Directory Cleanup via Bash Script

I Mac Terminal

This is a simple BASH script that I used to sort a folder that has a lot of images. I wanted to put photos in a folder based on the date it was created.

This script will work in any environment, but I wrote this specifically to handle a large set of photos in a folder on my Macintosh.

#!/bin/bash
for f in *; do
dir=$(stat -f%SB -t%Y-%m-%d "$f")
echo $f '->' $dir
[ -d "$dir" ] || mkdir "$dir"
mv "$f" "$dir"/
done

What this Script Does

When you execute this script in any directory, it will use the UNIX stat command to check on the time stamp on the file. It will then move the file to a folder with the same. If the directory doesn't exist then one will be created.

Script Execution

Create a file with the above content. I call my file sort.sh. Move the file to any directory that you want to clean up. To execute, simply type in:

./sort.sh

In a few minutes you'll see the contents of the folder be replace with a bunch of date folders. (Yes even the sort.sh file will get moved to a folder.)

Comments

Add your Comments

Feel free to leave a comment about this post.

- Feel Free to add HTML to your comment!