Loading

提交GIT代码同步更新到服务器 钩子

#!/bin/bash
echo ""
# 输出当前时间
date --date='0 days ago' "+%Y-%m-%d %H:%M:%S"
echo "Start"
 
# git项目路径(这里根据自己的项目路径进行修改)
gitPath="/www/wwwroot/xxx"
# git网址(这里根据自己的Git地址进行修改)(ssh的地址||http地址)
gitHttp="git@xxx.git"
echo "Web站点路径:$gitPath"
 
#判断项目路径是否存在
if [ -d "$gitPath" ]; then
        cd $gitPath
        echo "打开路径"
        #判断是否存在git目录
        if [ ! -d ".git" ]; then
                echo "在该目录下克隆 git"
                sudo git clone $gitHttp gittemp
                sudo mv gittemp/.git .
                sudo rm -rf gittemp
        fi
        
         # 检查远程分支的最新提交
        latestRemoteCommit=$(git ls-remote origin master | awk '{print $gitPath}')
        echo "远程分支最新提交:$latestRemoteCommit"
        
        # 检查当前分支
        currentBranch=$(git rev-parse --abbrev-ref HEAD)
        echo "当前分支:$currentBranch"
        
        # 如果当前不在需要的分支上,则切换分支
        if [ "$currentBranch" != "master" ]; then
            git checkout master || git checkout -b master origin/master
        fi
        
        # 拉取最新的项目文件
        echo "拉取最新的项目文件"
        git fetch --all
        currentLocalCommit=$(git rev-parse HEAD)
        echo "当前本地提交:$currentLocalCommit"
        
        # 检查是否有新的提交需要拉取
        if [ "$currentLocalCommit" != "$latestRemoteCommit" ]; then
            echo "拉取远程分支的最新提交"
            sudo git pull origin master
        else
            echo "本地已经是最新提交"
        fi
        
        # 输出 Git 状态和日志
        echo "Git 状态:"
        git status
        echo "Git 日志:"
        git log -1 --oneline
        echo "查看当前分支:"
        git branch
        echo "查看远程分支跟踪关系:"
        git branch -vv
    
        echo "拉取结束End"
        exit
else
        echo "该项目路径不存在"
        echo "新建项目目录"
        mkdir $gitPath
        cd $gitPath
        #判断是否存在git目录
        if [ ! -d ".git" ]; then
                echo "在该目录下克隆 git"
                sudo git clone $gitHttp gittemp
                sudo mv gittemp/.git .
                sudo rm -rf gittemp
        fi
        echo "拉取最新的项目文件"
        sudo git reset --hard origin/master
        sudo git pull
        echo "设置目录权限"
        sudo chown -R www:www $gitPath
        echo "End"
        exit
fi

 

posted @ 2025-07-14 11:10  路闻man  阅读(19)  评论(0)    收藏  举报