Git 命令大全
2025/2/24 19:39:40
来源:https://blog.csdn.net/qq_67572731/article/details/141886211
浏览:
次
关键词:Git 命令大全
Git 命令大全:全面详解
Git 是目前最流行的分布式版本控制系统,被广泛应用于软件开发中。无论是个人项目还是团队协作,掌握 Git 命令可以帮助你更有效地管理代码版本和协作开发。本文将详细介绍常用的 Git 命令,涵盖从基础操作到高级使用场景。
一、Git 基础命令
1. 初始化仓库
-
git init
用于在当前目录下初始化一个新的 Git 仓库。
git init
2. 配置 Git 用户信息
3. 查看仓库状态
-
git status
查看当前仓库的状态,显示有哪些文件发生了变化、哪些文件需要提交。
git status
4. 添加文件到暂存区
-
git add <file>
添加指定文件到暂存区。
git add README.md
-
git add .
添加当前目录下的所有变化到暂存区。
git add .
5. 提交更改
6. 查看提交历史
二、分支管理
1. 创建和切换分支
-
git branch <branch-name>
创建新分支。
git branch feature-branch
-
git checkout <branch-name>
切换到指定分支。
git checkout feature-branch
-
git checkout -b <branch-name>
创建并切换到新分支。
git checkout -b new-feature
2. 合并分支
-
git merge <branch-name>
将指定分支的内容合并到当前分支。
git merge feature-branch
3. 删除分支
4. 查看分支
-
git branch
查看本地分支列表,当前分支会标有 *
。
git branch
-
git branch -a
查看本地和远程的所有分支。
git branch -a
三、远程仓库操作
1. 查看远程仓库
-
git remote
查看配置的远程仓库。
git remote
-
git remote -v
查看远程仓库的详细信息,包括 fetch
和 push
的 URL。
git remote -v
2. 添加远程仓库
3. 推送到远程仓库
-
git push <remote> <branch>
将本地分支推送到远程仓库。
git push origin main
-
git push -u <remote> <branch>
推送并设置默认上游分支,以后可以直接用 git push
推送。
git push -u origin main
4. 拉取远程仓库的变化
-
git pull <remote>
拉取远程仓库的最新变化并合并到当前分支。
git pull origin main
-
git fetch <remote>
从远程仓库拉取最新的变化但不合并。
git fetch origin
四、标签管理
1. 创建标签
2. 查看标签
-
git tag
查看所有标签。
git tag
-
git show <tag-name>
查看指定标签的详细信息。
git show v1.0.0
3. 推送标签到远程仓库
-
git push <remote> <tag-name>
将指定标签推送到远程仓库。
git push origin v1.0.0
-
git push --tags
推送所有标签到远程仓库。
git push --tags
4. 删除标签
五、查看与比较
1. 查看提交差异
2. 查看文件历史
-
git log <file>
查看指定文件的提交历史。
git log README.md
-
git blame <file>
查看文件每一行的提交者和修改时间。
git blame README.md
3. 撤销操作
六、暂存与恢复
1. 暂存修改
2. 查看和恢复暂存
-
git stash list
查看暂存列表。
git stash list
-
git stash apply
应用最近一次暂存的内容。
git stash apply
-
git stash pop
应用最近一次暂存的内容并删除该暂存。
git stash pop
-
git stash drop <stash>
删除指定的暂存。
git stash drop stash@{0}
七、Git 高级命令
1. 修改最后一次提交
2. Rebase 操作
-
git rebase <branch>
将当前分支的提交应用到指定分支的基础之上。
git rebase main
-
git rebase -i <commit>
交互式 rebase,可以合并、重排、删除历史提交。
git rebase -i HEAD~3
3. Cherry-pick 操作
-
git cherry-pick <commit>
将指定提交的更改应用到当前分支。
git cherry-pick 123abc
4. 变基冲突解决
-
git rebase --continue
继续进行 rebase,通常在解决冲突后使用。
git rebase --continue
-
git rebase --abort
取消当前的 rebase 操作,恢复到 rebase 前的状态。
git rebase --abort
八、Git 与 GitHub 协作
1. 生成 SSH 密钥
2. 添加远程仓库 URL
3. Fork 和 Pull Request
九、总结
掌握 Git 命令是开发人员必备的技能之一,从项目初始化、分支管理、远程协作到高级操作,Git 提供了丰富的工具来帮助开发者高效管理代码。本文介绍的命令只是 Git 功能的一部分,通过不断实践和探索,你将能够更灵活地运用 Git 进行版本控制和团队协作。