A simple shell script for deployment
In a previous post I wrote about using rsync to transfer a website to a remote server. That resulted in a nice rsync command. Let’s create a shell script that builds the Jekyll site and then runs the rsync command.
Writing shell scripts is new to me so I had to do a little research. Here are the steps:
I came across this line in a lot of scripts and always wondered what it was for. Now I know. It’s called a hash bang and tells your computer what program to run to interpret the script. In my case the bash
program should interpret the script. It includes a nice trick that uses the env
program to search for bash
on the user’s computer. See this excellent post on Stackoverflow for more information.
To make the script easier to read I use some variables. For an explanation of the first four variables see my earlier post on rsync. The last variable tells the script where the Jekyll source directory is. I placed the deployment script outside the source directory. The script isn’t really part of the website, so it shouldn’t be in the website’s source directory.
The next step builds the website using Jekyll.
Then I though: “What if the Jekyll build fails?”. It is unnecessary to do an rsync in that situation. Again Stackoverflow came to the rescue. The variable $?
contains the result of the last command. A value of 0 means succes. So I use a conditional statement to test if the result is not equal to 0. The conditional statement exits the script with the value of 1, indicating that the script itself failed. In this case not really necessary because there are no other scripts that depend on this script. But it seems good coding practice.
The last part of the script runs the rsync command explained here and exits the script with a succes status.
I know there are fancier methods for writing a deployment script. For example by using Fabric, Rake or Grunt. I’ll look into those in the future. But for now: this script works for me.
Ps. If you use version control like git, make sure the branch you want to deploy is in your source directory. The git workflow isn’t part of this script, that’s something on my to-do list.