[Git] Moving A Git Repository To A New Server

[更新]有更簡潔的做法,請參考 Duplicating a repository

在工作上遇到要將git repository從舊的server轉移到新的sever,參考這篇文章Moving A Git Repository To A New Server進行轉移.

Step 1: fetch所有的remote branch

1
git fetch origin

Step 2: 將所有remote branch clone到本地端

1
2
3
4
5
for branch in `git branch -a | grep remotes | grep -v HEAD`; do
git branch --track ${branch##*/} $branch
done
git fetch --all
git pull --all

Step 3: 新增新的repository,名稱為new-origin

1
git remote add new-origin git@[new server url]:[group]/[project].git

Step 4: push所有的branch和tag到新的repository

1
2
git push --all new-origin
git push --tags new-origin

Step 5: 砍掉舊的repository,並且新的repository改名為origin

1
2
git remote rm origin
git remote rename new-origin origin

將以上的操作步驟寫成script:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#!/bin/bash
rm -rf $1
git clone git@old-repo:old-group/$1.git
cd $1
git fetch origin
for branch in `git branch -a | grep remotes | grep -v HEAD`; do
git branch --track ${branch##*/} $branch
done
git fetch --all
git pull --all
git remote add new-origin git@new-repo:new-group/$1.git
git push --all new-origin
git push --tags new-origin
git remote rm origin
git remote rename new-origin origin

參考: