日常学习和工作中都需要使用到git来管理项目,有些命令不常用容易忘记,整理一下。
学习git指令推荐廖雪峰老师的教程 Git教程
1-安装Git
Git官网download 根据系统来安装就可以,安装完成后设置自己的username和Email地址
$ git config --global user.name "Your Name"
$ git config --global user.email "email@example.com"
注意git config命令的--global参数,用了这个参数,表示你这台机器上所有的Git仓库都会使用这个配置,当然也可以对某个仓库指定不同的用户名和Email地址。
2-生成公钥私钥并配置
1)windows打开本地Git Bash输入如下命令生成公钥私钥
ssh-keygen -t rsa -C 'xxx@xxx.com'
2)打开公钥文件
路径~/.ssh/id_rsa.pub
(~表示用户目录,windows就是C:\Users\用户名),复制其中的内容。
3)私有化项目,添加公钥。
找到git仓库的添加SSH Keys的地方并把上一步中复制的公钥内容粘贴并添加key。
4)配置多个ssh key
做法如下:(以公司gitlab和github为例):
为gitlab生成一对秘钥ssh key
ssh-keygen -t rsa -C 'yourEmail@xx.com' -f ~/.ssh/gitlab-rsa
为github生成一对秘钥ssh key
ssh-keygen -t rsa -C 'yourEmail2@xx.com' -f ~/.ssh/github-rsa
在~/.ssh目录下新建名称为config的文件(无后缀名)。用于配置多个不同的host使用不同的ssh key,内容如下:
# gitlab
Host gitlab.com
HostName gitlab.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/gitlab_id-rsa
# github
Host github.com
HostName github.com
PreferredAuthentications publickey
IdentityFile ~/.ssh/github_id-rsa
配置文件参数
Host : Host可以看作是一个你要识别的模式,对识别的模式,进行配置对应的的主机名和ssh文件
HostName : 要登录主机的主机名
User : 登录名
IdentityFile : 指明上面User对应的identityFile路径 按照上面的步骤分别往gitlab和github上添加生成的公钥gitlab_id-rsa.pub和github_id-rsa.pub
此时,再次查看~/..ssh目录下的文件,会有gitlab_id-rsa、gitlab_id-rsa.pub和github_id-rsa、github_id-rsa.pub四个文件
3-新建本地仓库并clone项目
git init
git clone 你项目的 SSH 公钥直接复制粘贴
4-创建本地分支
两种写法:
$ git checkout -b dev
或
$ git branch dev //创建dev分支
$ git checkout dev //切换到dev分支
4-更新并提交分支
$ git status // 查看状态
$ git stash // 放入缓冲区
$ git stash list //
$ git checkout master // 切换到主分支
$ git pull // 把最新的主分支数据拉下来
$ git branch // 查看当前的分支
$ git checkout dev // 切换到我的分支
$ git merge master // 合并分支
$ git stash pop // 将缓冲区的东西提出来
$ git status // 查看状态
$ git add * // 修改或添加所有
$ git commit -m "注释" // 提交修改
$ git push // 把你自己分支的内容提交到远程自己的分支
第一次提交分支:
git push --set-upstream origin dev//往远程仓库新建并提交dev分支
5-版本退回
$ git log //查看版本信息
$ git reset --hard HEAD^ //退回上一commit提交的版本
$ git reset --hard 1094a //退回指定版本,版本信息在log中查看
$ git reflog //查看每次命令
6-一些别的命令
$ git diff HEAD -- readme.txt //查看该文件区别
$ git checkout -- readme.txt //撤销该文件修改,注意--,与且分支不同
$ rm test.txt //删除文件
$ git rm test.txt //版本库中删除
7-自己的远程仓库项目
1)创建好远程仓库
2)关联
$ git remote add origin git@远程仓库地址
3)推送到远程仓库
$ git push -u origin master //第一次提交
$ git push origin master //后面的提交
当你第一次使用Git的clone或者push命令连接GitHub时,会得到一个警告:
The authenticity of host 'github.com (xx.xx.xx.xx)' can't be established. RSA key fingerprint is xx.xx.xx.xx.xx. Are you sure you want to continue connecting (yes/no)?
这是因为Git使用SSH连接,而SSH连接在第一次验证GitHub服务器的Key时,需要你确认GitHub的Key的指纹信息是否真的来自GitHub的服务器,输入yes回车即可。
Git会输出一个警告,告诉你已经把GitHub的Key添加到本机的一个信任列表里了:
Warning: Permanently added 'github.com' (RSA) to the list of known hosts.