个人博客自动更新脚本
个人博客自动更新脚本
在使用jekyll的Chirpy theme构建个人博客的时候,经常需要commit和push,重复性的劳动是一件很无聊的事,于是想到可以用一个bash脚本去自动化完成这一工作。
脚本
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
#!/bin/bash
REPO_PATH="/path/to/your/repo"
LOG_FILE="/path/to/your/log/directory/blog-auto-commit.log"
cd "$REPO_PATH" || {
echo "Failed to change to repository directory" >> "$LOG_FILE"
exit 1
}
DATE=$(date +"%Y-%m-%d %H:%M:%S")
# Function to attempt git push with retry
git_push_with_retry() {
local max_attempts=3
local attempt=1
local delay=30
while [ $attempt -le $max_attempts ]; do
if git push origin main >> "$LOG_FILE" 2>&1; then
return 0
else
echo "Push attempt $attempt failed, waiting $delay seconds..." >> "$LOG_FILE"
sleep $delay
attempt=$((attempt + 1))
fi
done
return 1
}
if git status --porcelain | grep '^.*$' >/dev/null; then
git add . >> "$LOG_FILE" 2>&1
if git commit -m "Auto-commit: $DATE" >> "$LOG_FILE" 2>&1; then
if ! git_push_with_retry; then
echo "Failed to push after multiple attempts at $DATE" >> "$LOG_FILE"
exit 1
fi
else
echo "Failed to commit changes at $DATE" >> "$LOG_FILE"
exit 1
fi
else
echo "No changes to commit at $DATE" >> "$LOG_FILE"
fi
运行
可以将脚本放置于~/bin
目录下,并且赋予其执行权限:chmod +x script.sh
。然后需要讲该脚本加入cron job中,运行crontab -e
,填入以下内容:
1
0 * * * * ~/bin/script.sh
This post is licensed under CC BY 4.0 by the author.