Skip to content

Sorting files in git by creation date

Sort files by creation date using git history: a bash loop that finds the first commit of each file, which I used to order SQL migrations.

1 min read

Since GNU/Linux (or any other POSIX-compatible operating system) does not store file creation dates as a standard we can instead get the file creation date using git. This is provided you are using git for your project, of course.

To sort files by creation date in git you can do something like this:

TIMESTAMPS=(); for file in `ls`;
do TIMESTAMP=`git log --format=%at -- $file | tail -1`;
TIMESTAMPS+="$TIMESTAMP-$file";
done;
echo $TIMESTAMPS | tr " " "\n" | sort -n | cut -d- -f2-

There probably is a more elegant way of doing it, but it worked fine for me. This proved very useful when I sorted our existing SQL migrations in order to apply them sequentally. We did not have any ordering in the file names which determined the order in which they were run.