Create Hugo Posts With Bash

Ok. This one is by far the most powerful trick in my Hugo arsenal and I feel like sharing it because it is a HUGE time saver.

We all know about Hugo’s archetypes. But they’re only for front matter.

How about creating content pages for several products that have essentially the same text and a different photo or barcode.

I’m using the readDir function to render photos in my content pages. A while back I posted a tutorial on how to do this over here: Per-post thumbnail through filename convention?

Now here is what I do. I move the photos I need in a folder. Each photo has the desired permalink in its filename.

And then in this folder I created a hugopost.sh and with the following contents:

#!/usr/bin/env bash

## iterate through each file whose name ends in 'jpg'
## saving it as $file. ~ is your $HOME directory
for file in ~/*jpg
do
    ## basename will remove the path (~/Desktop/My_pictures) and also
    ## remove the extension you give as a second argument    
    name="$(basename "$file" .jpg)"

    ## create the directory, the -p means it will create 
    ## the parent directories if needed and it won't complain
    ## if the directory exists.
    mkdir -p ~/"$name"
    touch "$name".md

echo '+++
brand = "Some brand"
title = "Some title"
barcode = "Some number"
description = "Lorem Ipsum Dolor Si Amet"
dimensions = "Whatever"
image = "/images/'$name'-thumb.jpg"
tags = [ "some-tag" ]
+++' > "$name".md

    ## copy jpg to /images/
    mv "$file" "~/$name"
    ## move directory to hugo static
    mv "~/$name" "path to directory"
    ## move md to hugo content
    mv "~/"$name".md" "path to directory"
done

Of course you need to fill the directory paths and change the content of your front matter parameters to whatever you need. Then make hugopost.sh executable with chmod +x or using your desktop’s file properties GUI.

And simply run ./hugopost.sh in the directory with the photos and the script.

Enjoy!

PS Obviously this is is for Linux. And I got it to work from bits and pieces on the Ask Ubuntu Forum. I’m sure you can get it to work on MacOs since it’s also UNIX. But I don’t know anything about Windows and don’t ask me how to make this work on Microsoft’s Os.

5 Likes

well, if you are running Windows 10, you can install Bash natively and do this. Or, you can install Bash for Git and do this also.