通过githook自动更新代码

  1. 背景:在公司搭建了gitlab,已经具备了CI/CD 的能力。但喜欢折腾,刚好今天有空。盘它。下面就是代码

 

#!/bin/bash

# 项目地址
REPO_PATH="/path/to/your/repo"
BRANCH="master"
LOG_FILE="/var/log/git_hook_monitor.log"

# 进入项目目录
cd "$REPO_PATH" || exit 1

echo "[INFO] Monitoring Git repository: $REPO_PATH" | tee -a "$LOG_FILE"

# 获取远程最新提交的哈希值
latest_remote_commit() {
    git ls-remote origin "$BRANCH" | awk '{print $1}'
}

# 获取本地最新提交的哈希值
latest_local_commit() {
    git rev-parse "$BRANCH"
}

while true; do
    REMOTE_COMMIT=$(latest_remote_commit)
    LOCAL_COMMIT=$(latest_local_commit)

    if [ "$REMOTE_COMMIT" != "$LOCAL_COMMIT" ]; then
        echo "[INFO] New push detected on master. Pulling latest changes..." | tee -a "$LOG_FILE"
        git pull origin "$BRANCH" | tee -a "$LOG_FILE"
    fi

    # 每 10 秒检查一次
    sleep 10
done

3 加权限,然后执行就行

posted @ 2025-02-08 18:04  专心写代码  阅读(18)  评论(0)    收藏  举报