Gatsby Post Generation

Simple bash scripting to generate Gatsby blog posts

In a classic case of ignoring XKCD’s advice, I threw together a simple script to generate Gatsby blog posts files. I’m sure other generating scripts exist out there on the internet, but a cursory search didn’t return any that fit my needs.

One of the hallmarks of a Gatsby blog post is the frontmatter at the top:

title: Your Title Here
date: "2020-04-19"
description: Basic description about your post
tags: ["tag1", "tag2"]

While it’s not that much boilerplate to write, adding this over and over again can be annoying. If you make a mistake in your date, your posts can show up out of order. If you happen to use those dates in your directory hierarchy, you end up copying today’s date over and over for each post. My blog content is nested first by year and then by a combination of date + name, like this:


I wanted this script to:

  1. Build the directory structure, including the parent-year directory if it doesn’t exist
  2. Name the post directory with a combination of today’s date and the post title
  3. Create an markdown file with frontmatter, including the provided title and description
  4. Handle inserting today’s date wherever necessary

TLDR: Here’s the script.


#define parameters which are passed in.

#generate variables
d=`date +%Y-%m-%d`
y=`date +%Y`

#create year directory if necessary
    echo "Parent directory $PARENT_DIRNAME exists"
    echo "Creating directory $PARENT_DIRNAME"

echo "generating directory: $DIRNAME"
mkdir $DIRNAME

echo "creating $FILENAME"

#define the template.
cat << EOF > $FILENAME
title: $TITLE
date: "$d"
description: $DESCRIPTION
tags: []
placeholder text

I put this file in /scripts in the parent folder of this website, and added the following line to scripts in package.json to let me call the script through yarn:

"generate-post": ". ./scripts/"

You can use this command in the terminal like so:

> yarn generate-post "your title" "your description"

which will generate the following file as content > blog > 2020 > 2020-04-19_your-title >

title: your title
date: "2020-04-19"
description: your description
tags: []
placeholder text

Pretty simple, and I’ve already spent too much time on it. Feel free to take this script and make it your own. Happy generating!

A quick update 6/9/2020:

In preparation for migrating a few of my pieces from Medium to this blog, I needed the ability to optionally define the date for the post. I added this by making the following changes to the #generate variables portion of the script:

d=${3:-`date +%Y-%m-%d`}
y=`echo $d | cut -c1-4`

This does two things:

  1. Sets the date to one passed in (expecting a YYYY-DD-MM format), otherwise uses date.
  2. Sets the year to the first 4 characters of the datestring (where it was previously generated using date, redundantly).

Also, you can now grab the code from this codebin, hope that’s a little more useful.