Bootstrap

2030. gitLab A仓同步到B仓

1 A 仓库备份 到 B 仓库

#!/bin/bash

# 定义变量
REPO_DIR="/home/xhome/opt/git_sync/zz_xx_xx"  # 替换为你的本地库A的实际路径
REMOTE_ORIGIN="http://192.168.1.66:8181/zzkj_software/zz_xx_xx.git"        # 库A的URL
REMOTE_BACKUP="http://192.168.1.67:8181/zzkj_software/zz_xx_xx.git"  # 库B的URL
BRANCH_NAME="main"  # 分支名称

# 进入仓库目录
cd "$REPO_DIR" || exit

# 检查是否有新的提交到 REMOTE_BACKUP
echo "Checking for new commits on REMOTE_BACKUP..."
git fetch "$REMOTE_BACKUP" "$BRANCH_NAME"
if [ $(git rev-list --count HEAD...FETCH_HEAD) -gt 0 ]; then
    echo "WARNING: There are new commits on REMOTE_BACKUP. These will be overwritten."
    read -p "Do you want to continue and force push? (y/n): " choice
    if [ "$choice" != "y" ]; then
        echo "Aborting."
        exit 1
    fi
fi

# 获取最新的远程信息,并记录远程分支的最新提交哈希值
echo "Fetching the latest changes from REMOTE_BACKUP..."
git fetch "$REMOTE_BACKUP" "$BRANCH_NAME"
REMOTE_BRANCH_HASH=$(git rev-parse FETCH_HEAD)

# 强制推送更新到远程备份库,使用 --force-with-lease 并指定预期的远程分支哈希值
echo "Pushing updates to REMOTE_BACKUP with --force-with-lease..."
if ! git push --force-with-lease="refs/heads/$BRANCH_NAME:$REMOTE_BRANCH_HASH" "$REMOTE_BACKUP" "$BRANCH_NAME"; then
    echo "Failed to push updates to REMOTE_BACKUP. Please check your repository state."
    exit 1
fi

# 强制推送所有标签到远程备份库
echo "Pushing tags to REMOTE_BACKUP..."
if ! git push "$REMOTE_BACKUP" --tags; then
    echo "Failed to push tags to REMOTE_BACKUP. Please check your repository state."
    exit 1
fi

# 可选:清理本地不再需要的远程跟踪分支和标签
# git remote prune backup

echo "Synchronization completed successfully."

2 B 仓库修改main分支的权限

  • main 分支允许强制推送即可.
    在这里插入图片描述
;