在mac终端中使用git(适用于github、gitlabel)
一、升级安装git
使用终端升级指令: git clone https://github.com/git/git
二、SSH-Keys准备
使用终端生成.ssh文件
1.判断电脑是否已存在.ssh文件
由于.ssh文件夹默认路径为~/.ssh,故直接判断该路径下是否存在该文件夹
cd ~/.ssh //不存在时结果: No such file or directory
mkdir ~/.ssh //根目录下创建.ssh文件夹
cd ~/.ssh //进入根目录

2.生成.ssh文件(当电脑中不存在.ssh文件)
终端指令: ssh-keygen -t rsa -C "注册github/gitlab时使用的邮箱" //反馈结果: Enter file in which to save the key (~/.ssh/id_rsa): 此时直接回车则在默认路径下生成id_rsa等文件,若输入自定义路径,则在自定义路径中生成(注意: 若在自定义路径中生成,通过默认路径调取.ssh文件夹将失败,暂时不清楚如何指定默认路径,现只用作备份多个.ssh,需要使用时,覆盖默认路径中.ssh文件)
PS: 对于需要配置多个SSH-Key以对应多个服务端的,后文补充介绍多SSH-Key的配置。


三、git准备
创建SSH-Keys


此处key使用上文创建 .ssh/id_rsa.pub 的内容,title可任意命名
查看id_rsa.pub文件的方法
1.通过终端
cd ~/.ssh
open id_rsa.pub //or vim id_rsa.pub


2.通过Finder
打开Finder -> shift + command + G (地址: ~/.ssh)

四、生成远程仓库



五、使用terminal完成git操作
1.从本地端上传数据至远程仓库
cd /.../指定路径/指定项目根目录 //定位至数据文件夹
git init //为本地库初始化git
git remote add origin [SSH地址] //设置远程仓库
git add . //添加变动至本地库
git commit -m 'commit description' //提交改动至本地库并附带描述,-m 表示暂存区/ -am 代表跟踪过的文件,可同时提交俩者,git commit -m -am 'commit description'
git push -u origin master //推送至远程仓库master,需要输入创建.ssh时创建的密码

2.从远程仓库拉取数据
cd /.../用于缓存的文件夹 //定位至待缓存数据文件夹
git init //为本地库初始化git
git remote add origin [SSH地址] //设置远程仓库
git pull origin master //从远程仓库master拉取数据,需要输入创建.ssh时创建的密码

3.其他设置
3.1修改仓库地址
//方法1
git remote origin set -url [新的SSH地址] //修改本地远程仓库
//方法2
git remote rm origin //删除本地仓库地址
git remote add origin [新的SSH地址] //设置本地远程仓库
//方法3
修改本地库内.git文件夹中的config文件 //url = [新的SSH地址]
3.2分支管理
git branch [新分支名] //创建分支
git checkout [分支名] //切换当前本地库对应的分支
git push origin [分支名] //推送至对应分支
git branch -d [待删除分支名] //本地库删除分支
git push origin :[分支名] //删除远程库分支
git branch //查看本地库所有分支
git merge [其他分分支名] //将其他分支与当前分支合并,此时当前分支变更,其他分支内容不改变
六、配置多个SSH-Key
1.生成SSH-Key
生成方法与上文相同
ssh-keygen -t rsa -C "注册时使用的邮箱" //该步完成时,需要设定对应的名字以提高辨析度
Enter file in which to save the key (…/默认路径): id_rsa_github
2.配置引导路径
2.1创建config文件
进入默认路径 ~/.ssh,生成文件config

2.2配置config文件的基本格式

# 注释名
Host github.com //服务器接口
HostName github //自定义服务器名,提高辨析
User 用户名 //对于github则不使用,gitlab则需要填入对应的账户
PreferredAuthentications publickey //权限设置,公钥
IdentityFile ~/.ssh/服务器对应的公钥文件名 //设置路径
以上即配置完毕,使用时,ssh会自动匹配对应的服务器