Git常用命令
发表于更新于
长沙
Git 常用命令参考
本文档涵盖了 Git 从基础配置到进阶操作的常用命令速查。
1. 环境配置
在开始使用 Git 前,通常需要设置用户名和邮箱,这些信息将包含在每一次提交中。
1 2 3 4
| git config --global user.name "Your Name" git config --global user.email "email@example.com" git config --global core.editor vim git config --list
|
2. 基础操作
初始化与克隆
1 2 3
| git init git clone <url> git clone <url> <folder>
|
文件状态与查看
1 2 3 4
| git status git diff git diff --staged git log --oneline
|
暂存与提交
1 2 3 4 5 6
| git add <file> git add . git add -A git commit -m "message" git commit -am "message" git commit --amend
|
3. 分支管理
💡 提示:Git 2.23+ 引入了 git switch 和 git restore,用来替代部分 git checkout 的功能,语义更清晰。
创建与切换
1 2 3 4 5 6 7 8 9 10 11 12 13
| git branch git branch -r git branch <name> git branch -d <name> git branch -D <name>
git checkout <name> git checkout -b <name>
git switch <name> git switch -c <name>
|
合并与变基
1 2 3
| git merge <name> git merge --no-ff <name> git rebase <name>
|
4. 远程操作
1 2 3 4 5 6 7 8 9 10 11
| git remote -v git remote add origin <url> git remote remove origin
git push origin <branch> git push -u origin <branch># 推送并建立跟踪关系(首次推送推荐) git push origin --delete <branch>
git pull origin <branch> git pull --rebase origin <branch> git fetch origin
|
5. 撤销与回退
这是最关键的部分,误操作时的救命稻草。
恢复文件
1 2 3 4 5 6 7
| git restore <file> git checkout -- <file>
git restore --staged <file> git reset HEAD <file>
|
重置提交
1 2 3
| git reset --soft HEAD~1 git reset --mixed HEAD~1 git reset --hard HEAD~1
|
安全回退
6. 暂存
当你正在开发新功能,需要临时切换去修复 Bug,但又不想提交当前半成品的代码时使用。
1 2 3 4 5 6
| git stash git stash save "message" git stash list git stash pop git stash apply git stash drop
|
7. 标签管理
常用于标记版本号(如 v1.0.0)。
1 2 3 4 5 6 7
| git tag git tag <name> git tag -a <name> -m "msg" git tag -d <name>
git push origin <name> git push origin --tags
|
8. 常用技巧与场景
查看指定文件的修改历史
1 2
| git log -p <file> git blame <file>
|
忽略文件权限变更
如果你在 Windows 和 Linux 之间切换,可能会遇到文件权限变更导致的 diff,可以使用:
1
| git config core.fileMode false
|
解决冲突后继续
当 git merge 或 git rebase 出现冲突时:
- 手动编辑文件解决冲突。
git add <file> 标记为已解决。
git commit (merge时) 或 git rebase --continue (rebase时)。
别名配置
为了提高效率,可以配置简写命令:
1 2 3 4 5
| git config --global alias.st status git config --global alias.co checkout git config --global alias.br branch git config --global alias.ci commit
|