git常用命令

git的用法。

最常用命令

  1. git status
  2. git reflog
  3. git add <file>
  4. git commit -m "comment"
  5. git push origin master
  6. git remote -v 查看远程仓库地址

回滚版本

  1. HEAD指向的版本就是当前版本,Git允许我们在版本的历史之间穿梭,使用命令git reset --hard commit_id
    穿梭前,用git log可以查看提交历史,以便确定要回退到哪个版本。
  2. 要重返未来,用git reflog查看命令历史,以便确定要回到未来的哪个版本。

撤销修改

  1. 未add,git checkout -- file
  2. add后, git reset HEAD file

分支操作

  1. 查看分支:git branch
  2. 创建分支:git branch <name>
  3. 切换分支:git checkout <name>
  4. 创建+切换分支:git checkout -b <name>
  5. 合并某分支到当前分支:git merge <name>
  6. 删除分支:git branch -d <name>
  7. 强行删除分支,git branch -D <name>
  8. 合并分支时,加上--no-ff参数就可以用普通模式合并,合并后的历史有分支,能看出来曾经做过合并,而fast forward合并就看不出来曾经做过合并。
  9. 先把工作现场git stash一下,然后去修复bug,修复后,再git stash pop,回到工作现场。
  10. 从远程拉取分支: git fetch拉取远程信息后,git checkout -b <name> origin/<name>
  11. 强制push到远程: git push --force origin dev:dev

merge指定commnit

1
git cherry-pick <commit>

参考http://stackoverflow.com/questions/881092/how-to-merge-a-specific-commit-in-git/881112#881112

忽略特殊文件

  1. .gitignore
  2. https://github.com/github/gitignore
  3. 我的idea java的gitignore
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
.idea
target
*.iml
out
gen
rebel.xml
### Java template
*.class
# Mobile Tools for Java (J2ME)
.mtj.tmp/
# Package Files #
*.jar
*.war
*.ear
# virtual machine crash logs, see http://www.java.com/en/download/help/error_hotspot.xml
hs_err_pid*

其他

  1. 命令git rm用于删除一个文件。
  2. 要关联一个远程库,使用命令git remote add origin git@server-name:path/repo-name.git
  3. 关联后,使用命令git push -u origin master第一次推送master分支的所有内容。此后,每次本地提交后,只要有必要,就可以使用命令git push origin master推送最新修改
  4. 切换远程仓库地址,git remote set-url origin <remote repo url>

alias

编辑~/.gitconfig

1
2
3
4
5
6
7
8
9
10
11
12
[alias]
cm = commit
co = checkout
lg = log --color --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --
remotes = remote -v
cleanup = git remotes branch --merged | grep -v '*' | xargs git branch -d
branches = branch -a
brs = branch -a
tags = tag -l
st = status -sb
ac = !git add -A && git commit
po = push origin

遇到的问题

add ssh key

1
ssh-keygen -t rsa -b 4096 -C "wzktravel@gmail.com"

测试连接

1
ssh -T git@github.com

Common reasons that contributions are not counted

Common reasons that contributions are not counted
很可能是因为没有关联自己的邮箱。

1
2
git config user.name "wzktravel"
git config user.email "wzktravel@gmail.com"

403 Forbidden while accessing github

修改 .git/config

1
2
3
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://github.com/wzktravel/hexo.git

1
2
3
[remote "origin"]
fetch = +refs/heads/*:refs/remotes/origin/*
url = https://wzktravel@github.com/wzktravel/hexo.git

然后输入密码即可。

使用vim作为默认编辑器

1
git config --global core.editor vim

参考