git 常用命令

0.原理

工作区直接跟暂缓区打交道,暂缓区跟版本库打交道

  • 从工作区中添加内容到暂缓区
  • 将暂缓区的内容提交到版本库
  • 从版本库中检出内容到工作区

1. 忽略本地指定文件、目录

在git下载到本地的目录中修改.git/info/exclude文件

例如git status时忽略所有的.pyc文件

#忽略以.pyc结尾的文件 
*.pyc
#忽略dbg文件&目录
dbg
#只忽略dbg目录
dbg/
#只忽略dbg文件
dbg
!dbg/

2. 撤销对文件的修改

场景:当文件修改了,但没有add,还原最后一次提交的内容

git checkout --filename

注:使用之前需要确认确实要放弃之前的修改,否则会使内容彻底丢失。

3. 取消暂存(add)的文件

场景:文件add了,但是突然想取消add操作,此时可用reset命令

git reset HEAD filename

4. 添加缓存(add)

git add file      :将文件添加缓存区
git add -u :将文件的修改、文件的删除,添加到暂存区。 git add . :将文件的修改,文件的新建,添加到暂存区。 git add -A :将文件的修改,文件的删除,文件的新建,添加到暂存区。

5. amend 补充提交

场景:当commit 完了以后突然意识到还有文件没有提交,这时不需要再add+commit,可以amend到上次commit中

git add filename
git commit --amend

执行完commit后,想撤回commit,怎么办?

git reset --soft HEAD^

6. 回退

先使用git log 查看 commit日志,找到需要回退的那次commit的 哈希值commit_id

git reset --hard <commit_id>
git push origin HEAD --force

7. git reset --hard 回滚以后 以后怎么再回去

 git log -g

8. git 还原某个特定的文件到之前的版本

以src/test.py为例

1. git log src/test/py 得到改文件的commit历史
2. 得到要回退版本的hash,如d98a0f565804ba639ba46d6e4295d4f787ff2949
3. checkout对应的版本,git checkout  d98a0f565804ba639ba46d6e4295d4f787ff2949 src/test.py
4. commit checkout下来的版本,git commit -m 'revert to previous version'

9. git报错:Please move or remove them before you can switch branches.

error: Your local changes to the following files would be overwritten by checkout:
.
.
.省略中间部分
.
Please move or remove them before you can switch branches.

出现这个错误时:可以通过以下的命令处理:

git clean  -d  -fx ""

注: 
1. x :表示删除忽略文件已经对Git来说不识别的文件 
2. d: 删除未被添加到git的路径中的文件 
3. f: 强制执行

10. 还原指定的文件

如果想拿远端Git服务器的最新版本(或指定版本)覆盖本地修改,可以用git pull,但这样会全面更新本地代码库

如果只想放弃本地工作所作修改(尚未add),可以用

git checkout file/to/path

如果想从远端库获取最新的更新,应先更新本地库,再跟新的本地

git fetch
git checkout origin/master file/to/path

11. 切换账号

$ git config --global user.name "jihite"
$ git config --global user.email xtcmhs@gmail.com

如果用了 –global 选项,那么更改的配置文件就是位于你用户主目录下的那个,以后你所有的项目都会默认使用这里配置的用户信息。

如果要在某个特定的项目中使用其他名字或者电邮,只要去掉 –global 选项重新配置即可,新的设定保存在当前项目的 .git/config 文件里。 

  

  

原文地址:https://www.cnblogs.com/kaituorensheng/p/5954187.html