Git 推送本地所有分支和拉取远程所有分支

版权声明:本文为博主(SimonLiu)原创文章,未经博主允许不得转载。 https://blog.csdn.net/toopoo/article/details/85260277

本文是另外一篇博文 Win10 Ubuntu子系统设置Git服务器和SSH Server 证书登录,实现win10和macOS源码同步 的一部分,单独拿出来说一下:

首先,设置好远程Git Server的ssh证书登录,假设用户名是git,远程服务器Host设置为nas (具体设置参考上述博文);

其次,设置好 ssh-agent 自启动,具体参考 Win10 cmd命令行,Powershell,Linux子系统Ubuntu bash自动启动ssh-agent

1. 推送本地所有分支

1.1 首先在远程服务器上初始化一个bare仓库,

$ sudo git init --bare smartlight.git

1.2 输入密码就可以看到初始化信息了

[sudo] password for git:
Initialized empty Git repository in /mnt/f/gitRepo/smartlight.git/

1.3 本地仓库添加remote路径

git remote add origin ssh://git@nas/mnt/f/gitRepo/smartlight.git

推送方法1:git push --all origin

$ git push --all origin -u

即可以看到类似下面的信息

Counting objects: 232, done.
Delta compression using up to 4 threads.
Compressing objects: 100% (214/214), done.
Writing objects: 100% (232/232), 8.08 MiB | 2.08 MiB/s, done.
Total 232 (delta 37), reused 0 (delta 0)
remote: Resolving deltas: 100% (37/37), done.
To ssh://nas/mnt/f/gitRepo/Smartlight.git
 * [new branch]      master -> master

将来再次push简单使用 git push 即可。

git push

推送方法2:git push --mirror

$ git push --mirror

 2. 首次克隆远程所有分支(mac)

注意,简单使用git clone 理论上已经获取远程的所有分支,但是如果你此时输入 git branch -a ,只能看到本地的master分支和remote的所有分支,如果你要在本地显示每个分支,需要分别checkout到相应的同名分支上。很遗憾git没有提供一个内置的功能让你一次性做这个事情,所以需要创建一个脚本。(以本人的macOS的zsh shell为例)。虽然 git clone 有一个 --mirror 参数,但是这个参数会让你完全复制 git server 的整个目录结构,它并不是你原先的工作目录结构。

2.1 首先,在shell profile (~/.zshrc)里面建立一个函数gclone(),方便将来使用,使用函数是因为通常bash里的alias不支持传递参数:

function gclone(){
    git clone ssh://git@nas/mnt/f/gitRepo/$1.git
}

 2.2 其次,source 使其生效。

>source ~/.zshrc 

2.3 然后,在~/目录创建一个脚本gpa.sh (gpa是git pull all的缩写),内容是

#!/bin/zsh
git checkout master ;
remote=origin ;
for brname in ` git branch -r | grep $remote | grep -v master | grep -v HEAD | awk '{gsub(/^[^\/]+\//,"",$1); print $1}' `;
do
    git branch -D $brname ;
    git checkout -b $brname $remote/$brname ;
done ;
git checkout master

2.4 给gpa.sh添加执行权限:

>chmod +x ~/gpa.sh

2.5 现在开始克隆远程仓库,输入 gclone smartlight ,

这个函数命令相当于 git clone ssh://git@nas/mnt/f/gitRepo/smartlight.git 

>gclone smartlight

Cloning into 'smartlight'...
remote: Counting objects: 232, done.
remote: Compressing objects: 100% (177/177), done.
remote: Total 232 (delta 37), reused 232 (delta 37)
Receiving objects: 100% (232/232), 8.08 MiB | 4.90 MiB/s, done.
Resolving deltas: 100% (37/37), done.

2.6 然后切换到这个目录

>cd smartlight

2.7 运行gpa.sh即可

>gpa.sh

3. 再次拉取所有分支(包括新建分支)

(windows需要在git bash中运行)

git branch -r | grep -v '\->' | while read remote; do git branch --track "${remote#origin/}" "$remote"; done
git fetch --all
git pull -all

参考文献:

1. ZSH alias with parameter

2. How to clone all remote branches in Git?

3. How to fetch all Git branches

猜你喜欢

转载自blog.csdn.net/toopoo/article/details/85260277