一键部署并备份你的博客
在上一篇 《创建你的第一个博客》 中,我们已经搭建了一个基本的博客系统,你已经可以使用喜欢的编辑器(推荐 VSCode) 进行文章编写,使用 Git 提交修改到 GitHub,由其自动部署到 GitHub Pages,读者就可以读取到你的新博文。
但是还存在一些问题,比如:
- 我们只提交了博客生成的数据,而博客原始数据并没有提交到 GitHub,如果你的博客源码丢失了,就无法找回;
- 编写博客后,我们需要手动进行 git 管理,没有实现自动化;
1. 管理你的博客原始数据
1.1 新建仓库
如 ilivelearnteach.com
注:建议为私有仓库,保护博客源码。
1.2 提交博客原始数据到 GitHub
# 进入你的博客目录
cd path-to-your-blog/
# ilivelearnteach.com 为新建的仓库名
git remote add origin https://github.com/ilivelearnteach/ilivelearnteach.com
# 提交内容
git add .
git commit -m "my blog code"
git branch -M main
# 提交博客到 github
git push -u origin main
2. 自动化脚本
想实现的目标是:每次创建或更新博文,执行 ./deploy.sh
命令,一键完成所有后续动作。
2.1 创建脚本
在博客根目录创建脚本文件 deploy.sh
,内容为:
#!/bin/sh
set -x
# 可以修改成自己的博客名
printf "\033[0;32m ilivelearnteach.com Deploying updates to GitHub...\033[0m\n"
cd $(dirname "$0")
# Commit changes.
msg="rebuilding site $(date)"
if [ -n "$*" ]; then
msg="$*"
fi
# update the theme
git submodule update --remote
# remove old files
rm -rf public/*
# Build the project.
hugo
# Go To Public folder
cd public
# Add changes to git.
git add .
git commit -m "$msg"
# Push to blog repo and trigger building blog.
git push origin main
# push to source repo
cd ..
git add .
git commit -m "$msg"
git push origin main
2.2 运行脚本
# 修改文件属性为可执行(只需要第一次执行)
chmod +x deploy.sh
# 创建或修改博客
# 创建博客文章
hugo new post/my-second-post.md
# 然后打开文件 `ilivelearnteach.github.io/content/post/my-second-post.md`,
# 把 `draft: true` 改成 `draft: false`
# 执行脚本,自动提交博客源码和生成的博客到 GitHub,博客将自动更新
./deploy.sh
# 当然你可以写 commit 信息,记录本次博客更新的内容
# ./deploy.sh "Your optional commit message"