以下是Git最常用的20条命令及其核心用途说明,按功能分类整理,便于快速掌握日常开发所需操作:
📁 一、仓库初始化与基础操作
git init
初始化新仓库,创建空的Git仓库或重新初始化现有仓库。
git init
Bash
git clone [url]
克隆远程仓库到本地,完整复制代码库及历史记录。
git clone https://github.com/user/repo.git
Bash
git add [file]
将工作区文件添加到暂存区(Stage),支持通配符(如 git add . 添加所有变更)。
git add index.html # 添加单个文件
git add . # 添加所有修改
Bash
git commit -m "message"
提交暂存区文件到本地仓库,并附加提交说明。
git commit -m "修复登录页面样式"
Bash
git status
查看工作区与暂存区的文件状态(修改/未跟踪/已暂存)。
git status
Bash
git diff
显示工作区与暂存区的差异(未暂存的修改内容)。
git diff # 查看所有未暂存修改
git diff --staged # 查看已暂存文件的差异
Bash
🌿 二、分支管理
git branch
查看所有本地分支( -a 包含远程分支)。
git branch # 列出本地分支
git branch -a # 列出所有分支(含远程)
Bash
git branch [branch-name]
创建新分支(如 git branch feature-login )。
git branch feature-login
Bash
git checkout [branch-name]
切换分支( -b 可创建并切换,如 git checkout -b dev )。
git checkout main # 切换到main分支
git checkout -b hotfix # 创建并切换到hotfix分支
Bash
git merge [branch]
合并指定分支到当前分支(如 git merge feature )。
git checkout main
git merge feature-login # 将feature-login合并到main
Bash
git branch -d [branch]
删除本地分支( -D 强制删除未合并分支)。
git branch -d feature-old # 删除已合并分支
Bash
🌐 三、远程协作
git remote add [name] [url]
关联远程仓库(如 git remote add origin https://... )。
git remote add origin https://github.com/user/repo.git
Bash
git push [remote] [branch]
推送本地提交到远程仓库(如 git push origin main )。
git push origin main # 推送main分支
git push -u origin dev # 首次推送并设置上游分支
Bash
git pull [remote] [branch]
拉取远程分支更新并合并到当前分支(相当于 git fetch + git merge )。
git pull origin main
Bash
git fetch [remote]
下载远程最新变更但不自动合并(安全查看更新内容)。
git fetch origin # 获取远程更新
git diff main origin/main # 比较本地与远程差异
Bash
git remote -v
查看已配置的远程仓库地址。
git remote -v
Bash
⏪ 四、版本控制与撤销操作
git log
查看提交历史( --oneline 简化显示)。
git log # 详细历史
git log --oneline # 简洁版
Bash
git reset [commit]
回退到指定提交( --soft 保留变更, --hard 丢弃所有修改)。
git reset HEAD~1 # 回退到上一个提交(保留修改)
git reset --hard a1b2c # 强制回退到指定commit(丢弃修改)
Bash
git revert [commit]
撤销指定提交并生成新提交(安全撤销,不破坏历史)。
git revert d4e5f6 # 撤销commit d4e5f6的修改
Bash
git stash
临时保存未提交的修改(切换分支时常用)。
git stash # 保存当前修改
git stash pop # 恢复最近保存的修改
Bash
💎 总结
以上20条命令覆盖了Git日常使用的核心场景:
基础操作: init 、 clone 、 add 、 commit 、 status 、 diff
分支管理: branch 、 checkout 、 merge
远程协作: remote 、 push 、 pull 、 fetch
版本控制: log 、 reset 、 revert 、 stash
掌握这些命令可高效完成代码版本管理、分支协作与历史追溯。建议结合实践(如合并冲突处理)深化理解,更多高级用法可参考官方文档或社区教程。