A Safe Shell Script for Deploying a Hexo Blog

The original script stored commands in strings and executed them with eval. That works, but it also turns quoting mistakes into a small security workshop. Shell commands can be called directly.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#!/usr/bin/env bash
set -Eeuo pipefail

readonly GREEN='\033[0;32m'
readonly NC='\033[0m'
readonly DOMAIN='hdchinh.com'

log() {
printf '%b%s%b\n' "$GREEN" "$1" "$NC"
}

log 'Cleaning and generating the site'
hexo clean
hexo generate

log 'Creating CNAME'
printf '%s\n' "$DOMAIN" > public/CNAME

log 'Deploying'
hexo deploy

log 'Done'

set -Eeuo pipefail makes the script stop on failed commands, unset variables, and failed commands inside pipelines. printf is safer and more predictable than nested quoted echo commands.

Command chaining

1
2
3
A; B   # Run B regardless of whether A succeeds.
A && B # Run B only when A succeeds.
A || B # Run B only when A fails.

For deployments, && or strict mode is usually the sane choice. Publishing half a site because the build failed is technically automation, just not the useful kind.