0%

博客自动更新updated时间

提交博客的时候自动修改更新时间。

hexo博客在Markdown文件的前方,可以指定博客的发表时间和更新时间。

1
2
3
title: xxxxxxxx
date: 2021-09-09 23:04:19
updated: 2021-09-09 23:04:19

有时更新博客之后,会忘记更新updated字段。所以考虑使用git hooks自动化完成此任务。阅读git hooks文档后,发现pre-commit脚本可以很好的完成此任务,pre-commit脚本会在输入commit msg之前被执行。

还有一个问题,需要在脚本中拿到本次提交的文件列表。经过一番搜索,命令git diff --cached --name-only可以拿到这项信息。

经过上述的准备之后,简单组合之后,脚本就出来了。

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

# $1 file name
function update_updated_time()
{
local file_name=$1
if [ ! "$file_name" ]; then
exit 0
fi

updated_time=$(date +"%Y-%m-%d %H:%M:%S")
sed -i "1,10s/^updated.*$/updated: ${updated_time}/" $file_name
}

for file in $(git diff --cached --name-only)
do
update_updated_time $file
git add $file
done