ubuntu 利用shell脚本完成git多仓库定时备份

it2026-06-18  7

场景

从win服务器上将多仓库定时备份到ubuntu上,其实利用jenkins完全可以实现,当时组网时没考虑到将git(win)和jenkins(虚拟机)部署到一台机子上了,导致增加了后期的代码备份工作。

环境信息

操作系统 : Ubuntu 7.5.0-3ubuntu1~18.04 GIT版本 : git version 2.23.0.windows.1 目标路径 : /home/codebackup

脚本

#!/bin/bash cd /home/codebackup :<<! #以数组形式对工程进行克隆,仅首次使用,克隆完毕后注释掉 PROJECT=("http://192.168.1.138:3000/qskj/mindoffice.git" "http://192.168.1.138:3000/qskj/mindoffice-vue.git" "http://192.168.1.138:3000/yanghaiyan/fangke.git") for ((i=0;i<${#PROJECT[*]};i++)) do echo ${PROJECT[$i]} git clone ${PROJECT[$i]} done ! #ls显示后,截取空格为分隔符第9组且不包括bak的文件夹名称(以上数组为例1.txt内容为仓库名:mindoffice mindoffice-vue fangke) ls -l|grep ^d|awk -F ' ' '{print $9}'|grep -v bak$>>1.txt #读取文件 cat 1.txt |while read Dir do #进入对应仓库 cd $Dir #将远程主机内容拉取到本地,等用户确认无误后再手动进行合并;与git pull区别,后者拉取后直接合并 git fetch origin #显示出两个分支的差异部分 git diff --stat master origin/master |grep "changed" #当存在变化时执行后续语句输出日志文件,否则不予执行 if [ $? -eq 0 ];then echo "------------------------------------">>../codeback.log echo "项目名称: $Dir">>../codeback.log echo "同步时间:`date +%Y%m%d’`">>../codeback.log git pull>>../codeback.log fi cd ../ done #删除存放仓库名的文件 rm -rf 1.txt

定时任务

启动定时任务 crontab -e增加首行,每个半点去执行脚本增加完毕,输入ctrl+o,点击回车保存,再点击ctrl+x退出坑 ubuntu启用定时任务时千万不要使用绝对路径 执行脚本时务必加/bin/bash 执行时一定要有指定输出,不然执行不成功 30 * * * * cd /home/codebackup/&&/bin/bash backup2disk.sh >> /home/codebackup/build.log 2>&1 # Edit this file to introduce tasks to be run by cron. # # Each task to run has to be defined through a single line indicating with different fields when the task will be run and what command to run for the task # # To define the time you can provide concrete values for minute (m), hour (h), day of month (dom), month (mon), and day of week (dow) or use '*' in these # fields (for 'any').# Notice that tasks will be started based on the cron's system daemon's notion of time and timezones. # # Output of the crontab jobs (including errors) is sent through email to the user the crontab file belongs to (unless redirected). # # For example, you can run a backup of all your user accounts at 5 a.m every week with: 0 5 * * 1 tar -zcf /var/backups/home.tgz /home/ # # For more information see the manual pages of crontab(5) and cron(8) # # m h dom mon dow command
最新回复(0)