作为一位程序员,精通 Git 命令和使用技巧是非常重要的。以下是一些常用的 Git 命令和技巧汇总,帮助你更高效地管理代码版本控制。
基本命令
初始化仓库
git init
克隆仓库
git clone <repository-url>
查看仓库状态
git status
添加文件到暂存区
git add <file-or-directory>
# 添加所有文件
git add .
提交更改
git commit -m "Commit message"
查看提交历史
git log
查看简洁的提交历史
git log --oneline
分支管理
创建分支
git branch <branch-name>
切换分支
git checkout <branch-name>
创建并切换到新分支
git checkout -b <branch-name>
合并分支
git checkout <target-branch>
git merge <source-branch>
删除分支
git branch -d <branch-name>
远程仓库
查看远程仓库
git remote -v
添加远程仓库
git remote add <name> <url>
获取远程仓库更新
git fetch <remote>
拉取远程仓库更新并合并
git pull <remote> <branch>
推送本地更改到远程仓库
git push <remote> <branch>
标签管理
创建标签
git tag <tag-name>
查看标签
git tag
推送标签到远程仓库
git push <remote> <tag-name>
删除本地标签
git tag -d <tag-name>
删除远程标签
git push <remote> :refs/tags/<tag-name>
高级技巧
查看分支图
git log --graph --oneline --all
暂存当前更改
git stash
恢复暂存的更改
git stash pop
修改最后一次提交
git commit --amend
重置到特定提交
git reset --hard <commit-hash>
清理未跟踪的文件
git clean -f
交互式 rebase
git rebase -i <base-commit>
合作开发技巧
- 创建 Pull Request
- 推送分支到远程仓库git push origin <branch-name>
- 在 GitHub 上创建 Pull Request:导航到你的仓库,点击 Pull Requests,然后点击 New Pull Request。
解决冲突
- 拉取最新代码git pull origin <branch-name>
- 解决冲突:手动编辑冲突文件。
- 标记冲突文件为已解决git add <file>
- 提交解决冲突后的更改git commit
Git 配置
全局配置用户信息
git config --global user.name "Your Name"
git config --global user.email "[email protected]"
查看配置
git config --list
Git 别名
创建常用命令的别名可以提高效率:
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
其他有用的命令
查看某个文件的历史
git log -- <file>
查看某个文件在某次提交中的内容
git show <commit-hash>:<file>
比较两个分支的差异
git diff <branch1>..<branch2>
比较工作目录与暂存区的差异
git diff
比较暂存区与最新提交的差异
git diff --cached
通过掌握这些 Git 命令和技巧,你可以更高效地进行版本控制和团队协作。记住,实践是掌握这些技巧的关键,多多使用这些命令会让你在日常开发中更加得心应手。