多个git帐号的切换

来源:互联网 发布:java实验fan 编辑:程序博客网 时间:2024/06/05 05:50

公司的代码管理使用了git,同时个人在github上又有代码,以下方法可以同时访问两个git server.

1、新建github的SSH Key

# 新建SSH key

$cd ~/.ssh

# 切换到/Users/xxx/.ssh

ssh-keygen -t rsa -C"mygithub@email.com"

# 新建工作的SSH key#设置名称为id_rsa_github

Enter fileinwhich to save the key (/Users/xxx/.ssh/id_rsa): id_rsa_github

2、新密钥添加到SSH agent中

因为默认只读取id_rsa,为了让SSH识别新的私钥,需将其添加到SSH agent中:

ssh-add ~/.ssh/id_rsa_github

如果出现Could not open a connection to your authentication agent的错误,就试着用以下命令:

ssh-agent bashssh-add ~/.ssh/id_rsa_github

3、修改config文件

在~/.ssh目录下找到config文件,如果没有就创建:

touch config # 创建config

然后修改如下:
我的config配置如下:

# 该文件用于配置私钥对应的服务器

# Default github user(first@mail.com)

Host work.com 

HostName work.com 

User git 

IdentityFile/Users/xxx/.ssh/id_rsa

# second user(second@mail.com)

# 建一个github别名,新建的帐号使用这个别名做克隆和更新

Host github

HostName github.com 

User git 

IdentityFile/Users/xxx/.ssh/id_rsa_github

如果存在的话,其实就是往这个config中添加一个Host:

#建一个github别名,新建的帐号使用这个别名做克隆和更新

Host github

HostName github.com

User git

IdentityFile ~/.ssh/id_rsa_github

其规则就是:从上至下读取config的内容,在每个Host下寻找对应的私钥。

4、打开新生成的~/.ssh/id_rsa_github.pub文件,将里面的内容添加到GitHub后台。

可不要忘了添加到你的另一个github帐号下的SSH Key中。

5、测试:

lisc-mac:.ssh lishicong$ ssh -T github

Hi xxx! You've successfully authenticated, but GitHub does not provide shell access.

lisc-mac:.ssh lishicong$ 

6、 代码同步到github


git initgit add README.mdgit commit -m "first commit"git remote add origin git@github.com:xxx/xxx.gitgit push -u origin master
此处注意一点,原来的git@github.com:xxx/xxx.git需要修改为github:xxx/xxx.git

如果出现以下错误:fatal: remote origin already exists.

解决办法如下:

1、先输入$ git remote rm origin

2、再输入$ git remote add origin github:xxx/your-project-name.git 就不会报错了!

最后一步上传

git push -u origin master


如果出现以下错误

lisc-mac:Android-FastFramework xxx$ git push -u origin master

To github:lishicong/Android-FastFramework.git

 ! [rejected]        master -> master (non-fast-forward)

error: failed to push some refs to 'github:xxx/Android-FastFramework.git'

hint: Updates were rejected because the tip of your current branch is behind

hint: its remote counterpart. Integrate the remote changes (e.g.

hint: 'git pull ...') before pushing again.

hint: See the 'Note about fast-forwards' in 'git push --help' for details.

执行git pull命令,如果依然提示此错误,确保服务器代码无其他人修改的情况下,执行以下命令强制覆盖提交

git push --force -u origin master



0 0
原创粉丝点击