Linux: Sort files and directories by created date

I have a directory on my server where I’ve been throwing in files for years. It’s a complete mess and painfully slow to look though given the number of files in there.

So my rough-and-ready solution to the problem was to move each of the files and folders into a directory based on when they were added. I’ve deliberately kept it simple and not recursed into each sub-directory, since most of the files are downloads, and I’m only really interested in roughly when they were created.

The following script took less than a second to sort though a few hundred GB of files (since it’s moving them, and the target and source are on the same partition, it’s not very taxing).

I’ve been writing code for years, but bash is relatively new to me, so I’m very much open to comments and suggestions for improvements. Drop me a comment below.

#/bin/bash
# ------------------------------------------------------------------
# [David Claxton] Organise files based on date
#                 This script organises files into directories of
#                 .../year/month/... based on file creation dates
# 2015-01-28
# ------------------------------------------------------------------

BASE_DIR_IN="/some/directory/to/sort/Unsorted"
BASE_DIR_OUT="/some/directory/to/sort/Sorted"

NUMBER_OF_FILES=`ls -1 "$BASE_DIR_IN" | wc -l`

if [[ "$NUMBER_OF_FILES" -ne 0 ]]; then

	FILES="$BASE_DIR_IN/*"

	for current_file in $FILES
	do
		FILE_YEAR=`stat -c %y "$current_file" | sed 's/^\([0-9]\{4\}\)\-\([0-9]\{2\}\).*/\1/'`
		FILE_MONTH=`stat -c %y "$current_file" | sed 's/^\([0-9]\{4\}\)\-\([0-9]\{2\}\).*/\2/'`
		OUT_DIR="$FILE_YEAR/$FILE_MONTH"

		if [[ ! -d "$BASE_DIR_OUT/$FILE_YEAR" ]]; then
			mkdir "$BASE_DIR_OUT/$FILE_YEAR"
		fi

		if [[ ! -d "$BASE_DIR_OUT/$FILE_YEAR/$FILE_MONTH" ]]; then
			mkdir "$BASE_DIR_OUT/$FILE_YEAR/$FILE_MONTH"
		fi

		mv "$current_file" $BASE_DIR_OUT/$FILE_YEAR/$FILE_MONTH
	done

fi