git常用操作

 

使用前配置

设置用户名和email

git config --global user.name 'Your Name'
git config --global user.email 'your email'

生成秘钥

$ ssh-keygen -t rsa -C "liuchao102@163.com"
//生成完秘钥之后会在 C:UsersAdministrator.ssh 目录下 id_rsa和id_rsa.pub 两个文件,拷贝id_rsa.pub文件内容到 git 服务器上就可以了
//mac获取秘钥方法 $ cd ~/.ssh open ./
//每次都提示输入用户名和密码 git bash进入你的项目目录,输入:
git config --global credential.helper store
//然后你使用上述的命令配置好之后,再操作一次,然后它会提示你输入账号密码,这一次之后就不需要再次输入密码了
//用户名和密码为远程仓库的用户名和密码 

提交操作

某个文件更改之后

查看状态

git status //查看状态

对比文件

git diff [file] //查看某个文件工作区和暂存区的差别
git diff  //查看工作区和暂存区的所有差别

$ git diff --cached [file]
或
$ git diff --staged [file]//显示暂存区和上一次commit的区别

git diff [first-branch]...[second-branch] //显示两次提交的区别

添加到暂存区

git add <file> //添加某个文件的更改到暂存区
git add . //添加工作区所有更改到暂存区

添加到本地仓库

git commit -m <message> //提交到本地仓库,(保存一个快照) 

添加到远程仓库

git push origin [branchName]

撤销操作

# 撤销工作区更改(文件被修改了,但未执行git add操作)
$ git checkout fileName
$ git checkout .

# 撤销暂存区更改(文件执行了git add操作,没有commit )
$ git reset HEAD fileName 
$ git reset HEAD .

# 重置暂存区的指定文件,与上一次commit保持一致,但工作区不变
$ git reset [file]

# 重置暂存区与工作区,与上一次commit保持一致
$ git reset --hard

# 重置当前分支的指针为指定commit,同时重置暂存区,但工作区不变
$ git reset [commit]

# 重置当前分支的HEAD为指定commit,同时重置暂存区和工作区,与指定commit一致
$ git reset --hard [commit]

# 重置当前HEAD为指定commit,但保持暂存区和工作区不变
$ git reset --keep [commit]

# 新建一个commit,撤销指定commit
$ git revert [commit]

# 暂时将未提交的变化移除,稍后再移入
$ git stash
$ git stash pop

分支操作

# 查看分支
$  git branch 

# 创建分支
$ git branch name

# 切换分支
$ git checkout name 

# 创建并切换分支
$ git checkout -b <name> 

# 在本地创建和远程分支对应的分支
$ git checkout -b branch-name origin/branch-name 

# 新建一个分支,与指定的远程分支建立追踪关系
$  git branch --track [branch] [remote-branch]

#  建立追踪关系,在现有分支与指定的远程分支之间
$  git branch --set-upstream-to <branch-name> origin/<branch-name> 

# 删除本地分支
$ git branch -d <name>

# 丢弃一个没有被合并过的分支,强行删除
$ git branch -D <name>

# 删除远程分支
$ git push origin --delete <name>
# 合并某分支到当前分支 ,(--no-ff 普通合并模式)
$ git merge --no-ff -m 'fdfd' <name>
# 把某次提交转移到当前分支
$ git cherry-pick commitId

别名

# 设置别名
$ git config --global alias.his "log --pretty=format:'%h %ad | %s%d [%an]' --graph --date=short"
# 使用别名
$ git his

 tag标签

# 列出所有tag
$ git tag

# 新建一个tag在当前commit
$ git tag [tag]

# 新建一个tag在指定commit
$ git tag [tag] [commit]

# 删除本地tag
$ git tag -d [tag]

# 删除远程tag
$ git push origin :refs/tags/[tagName]

# 查看tag信息
$ git show [tag]

# 提交指定tag
$ git push [remote] [tag]

# 提交所有tag
$ git push [remote] --tags

# 新建一个分支,指向某个tag
$ git checkout -b [branch] [tag]
 

原文地址:https://www.cnblogs.com/liuxiaoru/p/13690879.html