Bash script for automatic Hugo site updates
On the bottom of this page you can see that this page is generated by hugo.
After nearly one year of blogging I finally invested some time to write a bash script which updates this blog automatically.
Although I think that scripts can be a little bit useless, when you don’t have exactly the same repository setup, you may want to adapt it. You can use it in a pipeline, after a commit hook or even manually!
Steps of the scripts
The script works with the folowing schema:
Download current state -> Create backup -> Generate new version -> Upload files.
Pre requisites
Obviously you need an installed hugo instance.
tar and scp are usually already available on most UNIX systems. But scp does the upload with a SSH key, accessed through the PRIVATE_KEY.
So you need to have access via an SSH key to your SFTP server.
The script
So here is it:
#!/bin/bash
# Usage:
# 1. Place this in the root of your hugo site.
# 2. Make it executable: chmod +x publish.sh
# 3. Set the following config variables.
BACKUP_ROOT_DIR=./backup
PRIVATE_KEY=~/.ssh/id_rsa
USER=
HOST=
REMOTE_DST_DIR=
CURR_DATE=$(date +"%Y-%m-%dT%H%M%S")
BACKUP_DIR=$CURR_DATE
DOWNLOAD_FILE_PATH=$BACKUP_ROOT_DIR/$BACKUP_DIR
BACKUP_FILE_COMPRESSED=$CURR_DATE.tar.gz
echo "Download current state from remote."
scp -i $PRIVATE_KEY -r $USER@$HOST:$REMOTE_DST_DIR $DOWNLOAD_FILE_PATH
if [ $? -ne 0 ]
then
echo "Download failed."
exit 1
fi
echo "Creating backup."
cd $BACKUP_ROOT_DIR
tar czvf $BACKUP_FILE_COMPRESSED $BACKUP_DIR
if [ $? -ne 0 ]
then
echo "Failed to compress backup file."
exit 1
fi
rm -rf $BACKUP_DIR
if [ $? -ne 0 ]
then
echo "Failed to delete raw backup directory. Check if you need to delete it manually: $BACKUP_DIR"
echo "Proceeding..."
fi
cd -
echo "Generate files to publish."
hugo
if [ $? -ne 0 ]
then
echo "Failed to generate files for upload."
exit 1
fi
echo "Start upload."
scp -i $PRIVATE_KEY -r ./public/* $USER@$HOST:$REMOTE_DST_DIR
if [ $? -ne 0 ]
then
echo "Failed to upload files."
exit 1
fi
echo "Finished :)"
echo "Backup File is located under $BACKUP_ROOT_DIR/$BACKUP_FILE_COMPRESSED"