使用git与sh脚本在pages上托管与更新gitbook

1 使用github仓库托管源代码

1.1 关联github仓库

思路:使用Gitbook Editor,或者Github客户端+VSCode在本地编辑源文件,然后同步到GitHub仓库中。

首先在github上新建仓库,命名为GitBook(也可以是其他任何合法名称),源代码将托管在master分支上。

在本地gitbook源文件根目录中初始化git仓库:

1
git init

然后创建名为.gitignore的文件,编辑其内容如下:

1
2
3
4
*~
_book
node_modules
.DS_Store

通过.gitignore文件,本地仓库将忽略临时文件和_book文件夹,达到只保存书籍源码的目的。然后运行:

1
2
3
4
git add .
git commit -m '_book'
git remote add github git@github.com:yourName/GitBook
git push -u github master

第一次push时可以使用
git push -u github master -f
来强制push。

2 使用–orphan命令发布_book文件夹

由于github在境外,故使用coding的仓库与静态pages服务托管gitbook页面。首先在coding中创建仓库,如cs-book,然后将本地静态页面上传到coding:

1
2
3
4
5
6
7
8
9
10
11
12
13
#在源文件根目录中初始化gitbook-cli服务
gitbook init
#安装插件
gitbook install
#生成静态页面,在./_book/文件夹中。
gitbook build

#新建分支
git checkout --orphan coding-pages
#删除不需要的文件
git rm --cached -r .
git clean -df
rm -rf *~

使用vim编辑.gitignore忽略文件:

1
2
3
4
*~
_book
node_modules
.DS_Store

复制_book文件夹到分支根目录:

1
2
3
4
5
6
7
8
9
10
cp -r _book/* .
#添加文件
git add .
#添加更新说明
git commit -m '_book'
#推送
git remote add coding git@git.dev.tencent.com:yourName/cs-book
git push -u coding coding-pages
#返回master
git checkout master

开启coding的pages服务即可查看页面

3 使用脚本进行更新

在gitbook文件根目录中添加deploy.sh文件:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#!bin/sh
git checkout master

#从github更新原文件并生成静态页面
git pull github master
gitbook build

#在coding-pages分支上进行操作
git checkout coding-pages
git rm --cached -r .
git clean -df
rm -rf *~
cp -r _book/* .
echo "node_modules
_book">.gitignore
git add .
git commit -m "cs-book"

#发布页面并返回主分支
git push -u coding coding-pages -f
git checkout master

为deploy.sh脚本授权:

1
chmod +x deploy.sh

以后运行sh deploy.sh就可以自动从github更新源文件、部署并发布到coding的托管Pages服务了。注意该脚本将静态页面部署在了coding-pages分支。

参考

将_book托管到Pages上

Shell脚本30分钟编程入门