0%

不可不会的git骚操作

最近一直在想着写博客,但是在github上面访问速度很慢,于是就在gitee上面也维护了一份相同的博客内容,这样就面临一个问题,电脑本地的项目怎么才能既推到github上面也能推到gitee上面????下面就来给各位介绍一波骚操作。

1.将项目推倒github或者gitee

这一步很简单,你在github/gitee新建一个项目,会给你提示操作,按着提示操作即可。

在gitee上面的提示

Git 全局设置:
1
2
git config --global user.name "用户名"
git config --global user.email "邮箱"
创建 git 仓库:
1
2
3
4
5
6
7
8
mkdir test
cd test
git init
touch README.md
git add README.md
git commit -m "first commit"
git remote add origin https://gitee.com/用户名/test.git
git push -u origin master
已有仓库?
1
2
3
cd existing_git_repo
git remote add origin https://gitee.com/用户名/test.git
git push -u origin master

在github上的提示

create a new repository on the command line
1
2
3
4
5
6
echo "# test" >> README.md
git init
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/用户名/test.git
git push -u origin master
push an existing repository from the command line
1
2
git remote add origin https://github.com/用户名/test.git
git push -u origin master
import code from another repository

You can initialize this repository with code from a Subversion, Mercurial, or TFS project.

2.将项目推倒另一个仓库

a.查看当前项目的远程仓库地址

这一步可以省略,这里只是想在做东西之前,做一下检查。这里以先推倒github为例。

1
2
3
$ git remote -v
origin https://github.com/用户名/test.git (fetch)
origin https://github.com/用户名/test.git (push)

b.添加另一个远程仓库

方式一:命令式
1
git remote add gitee  gitee项目地址
方式二:手动添加
1
2
3
4
[remote "gitee"]
url = gitee项目地址
fetch = +refs/heads/*:refs/remotes/gitee/*
tagopt = --no-tags

如果添加错了或者不想这样操作,可以使用下面命令删除,或者在config中手动删除

1
git remote rm gitee

c.再次查看远程仓库信息

1
2
3
4
5
$ git remote -v
gitee https://gitee.com/用户名/test.git (fetch)
gitee https://gitee.com/用户名/test.git (push)
origin https://github.com/用户名/test.git (fetch)
origin https://github.com/用户名/test.git (push)

d.提交到新添加的远程仓库

1
git push -u gitee

执行上面命令后,在自己的远程仓库会发现,项目已经被推送上去。

后续提交需要注意使用下面不同的脚本推送到不同的远程仓库。

1
2
git push -u origin
git push -u gitee

3.将项目一次推到多个仓库

如你所见,上面的方式我们需要推送两次,那么能不能推送一次就可以同时推送到githu和gitee呢,答案是当然可以

方式一:手动添加

1
2
3
4
5
//在config文件中添加
[remote "origin"]
url = 原有的git项目地址
fetch = +refs/heads/*:refs/remotes/origin/*
url = 新增的gitee项目地址

方式二:命令添加

1
git remote set-url --add origin gitee项目地址

这个时候是这样的

1
2
3
origin  https://github.com/xiaofeiyihui/myblog.git (fetch)
origin https://github.com/xiaofeiyihui/myblog.git (push)
origin https://gitee.com/xiaofeiyihui/myblog.git (push)

4.对比一次提交与两次提交

以上两种配置乍一看,配置3好像比配置2方便很多,少了一次push不是,其实不然,两种配置的不同还体现在pll代码上,配置2可以选择任一仓库进行pll,而配置3却默认只能从config中的第一个url内的仓库pull代码。pull代码的话配置2更方便,push代码的话配置3更方便。

小结

如果只是push操作,可以选用3;
如果涉及到pull操作,建议选用2.