git设置文件夹自动commit和push


set -e

常规情况下,有语句执行失败仍然会执行:

$ cat git_auto.sh 
cat notexists.txt
echo "hi"
$ bash git_auto.sh 
cat: notexists.txt: No such file or directory
hi

加上set -e后:

$ cat git_auto.sh 
set -e
cat notexists.txt
echo "hi"
$ bash git_auto.sh 
cat: notexists.txt: No such file or directory
$

执行失败会终止。

set -x

显示执行过程。

$ cat git_auto.sh 
set -e
set -x
echo 1
echo 2
echo 3
cat notexists.txt
echo "hi"
$ bash git_auto.sh 
+ echo 1
1
+ echo 2
2
+ echo 3
3
+ cat notexists.txt
cat: notexists.txt: No such file or directory

git自动提交

参考:git-auto

总结下来分为几个步骤:

  • 进入项目目录

  • git status查看状态

  • 判断是否更新

    • 没有
    • 有,git add然后commitpush,提交的info可以从git diff里面获取
  • 延时,循环

shell脚本:

cat git_auto.sh
# 前提:设置好git 本地和远程分支,使用git能够正常commit和push
set -e

project_dir="/home/pi/www"

cd ${project_dir} || (echo "wrong project dir" && exit -1)

while true
do
    if [[ $(git status) =~ "nothing to commit, working tree clean" ]]; then
        echo "nothing to commit"
    else 
        git add .
        git commit -m "$(git diff --name-only HEAD | sed -e 's/^.*\///')"
        git push origin master
    fi
    sleep $((1 * 60 * 60))
done

设置后台执行,记录日志:

nohup bash git_auto.sh 2>&1 > git_auto_info.txt &

拆开一看还挺简单的,就是判断是否有更改,有就提交。