云服务器上的目录定时同步到Github

具体操作与脚本

第一 在Github上创建私有仓库
这一步相信大家都知道怎么操作

第二 在服务器拉取Github仓库并把.git目录复制到需要同步的目录下
假设服务器需要同步的目录为:/usr/share/nginx/html/imgs

git clone git@github.com:xxxxxx/xxx.git
cd xxx
mv .git /usr/share/nginx/html/imgs/

cd /usr/share/nginx/html/imgs/
git init
git add .
git commit -am 'first commit'
git branch -M master
git push -u origin master

第三 编写定时同步脚本
具体脚本如下,如脚本位置: /root/script/sync_to_github.sh

#!/bin/bash

cd $1

has_push=false
untrack=`git status | grep 'Untracked files'`
if [ -n "$untrack" ]; then
  git add .
  has_push=true
fi
change_staged=`git status | grep 'Changes'`
if [ -n "$change_staged" ]; then
  git commit -am 'auto commit ...'
  has_push=true
fi

if [ "$has_push" = true ]; then
  git push
fi
chmod +x /root/script/sync_to_github.sh

第四 通过Linux的crontab表达式定时执行同步
编辑crontab

# vim /etc/crontab
SHELL=/bin/bash
PATH=/sbin:/bin:/usr/sbin:/usr/bin
MAILTO=root

# For details see man 4 crontabs

# Example of job definition:
# .---------------- minute (0 - 59)
# |  .------------- hour (0 - 23)
# |  |  .---------- day of month (1 - 31)
# |  |  |  .------- month (1 - 12) OR jan,feb,mar,apr ...
# |  |  |  |  .---- day of week (0 - 6) (Sunday=0 or 7) OR sun,mon,tue,wed,thu,fri,sat
# |  |  |  |  |
# *  *  *  *  * user-name  command to be executed
0 3 * * * root /root/script/sync_to_github.sh /usr/share/nginx/html/imgs

重启crond服务

# 我的服务器是Centos7 其他服务器请自行百度重启crond服务的方法
systemctl restart crond

版权声明:
作者:郭靖
链接:https://www.sxszhian.com/archives/8174
来源:上海永驰网络科技有限公司
文章版权归作者所有,未经允许请勿转载。

THE END
分享
二维码
打赏
< <上一篇
下一篇>>