Git 常用命令大全(2025 年最新实用版)
下面按使用频率和场景分类整理了最常用的 Git 命令,适合日常开发。所有命令都在终端(PowerShell、CMD、VS Code 终端)运行。
1. 基本配置(第一次用 Git 必做)
bash
git config --global user.name "你的名字" # 设置用户名
git config --global user.email "你的邮箱" # 设置邮箱
git config --global --list # 查看所有配置
2. 克隆仓库
bash
git clone https://github.com/xxx/yyy.git # HTTPS 方式
git clone git@github.com:xxx/yyy.git # SSH 方式(推荐,免密)
git clone https://code.iflytek.com/... # 公司内部仓库
3. 日常操作(本地开发)
bash
git status # 查看当前状态(哪些文件改了)
git add . # 添加所有改动到暂存区
git add 文件名 # 添加指定文件
git commit -m "提交信息" # 提交到本地仓库
git pull # 拉取远程最新代码(自动 merge)
git push # 推送本地提交到远程
git push origin branch-name # 推送到指定分支
4. 分支操作(超级常用)
bash
git branch # 查看所有本地分支
git branch -a # 查看本地 + 远程分支
git checkout 分支名 # 切换分支(旧方式)
git switch 分支名 # 切换分支(新推荐方式)
git switch -c 新分支名 # 创建并切换到新分支
git branch 新分支名 # 创建新分支
git push origin 新分支名 # 推送新分支到远程
git branch -d 分支名 # 删除本地分支
git push origin --delete 分支名 # 删除远程分支
5. 撤销与修复
bash
git log # 查看提交历史
git log --oneline # 简洁查看历史
git reset --soft HEAD~1 # 撤销最后一次 commit,但保留改动
git reset --hard HEAD~1 # 强行撤销最后一次 commit(小心!)
git revert commit-id # 生成新 commit 撤销指定提交(安全)
git checkout -- 文件名 # 丢弃文件改动(恢复到上次 commit)
git stash # 暂存当前改动(切换分支时有用)
git stash pop # 恢复暂存的改动
6. 远程仓库管理
bash
git remote -v # 查看远程仓库地址
git remote add origin 仓库地址 # 添加远程仓库
git remote set-url origin 新地址 # 修改远程地址(HTTPS ↔ SSH)
7. 高级实用命令
bash
git pull --rebase # 拉取时用 rebase(保持历史线性)
git fetch # 只下载远程更新,不合并
git merge 分支名 # 合并指定分支到当前
git cherry-pick commit-id # 挑取指定 commit 到当前分支
git diff # 查看未暂存改动
git diff --staged # 查看已暂存改动
8. 常见问题快捷解决
-
每次 push 都要输入密码 :配置 SSH 密钥(推荐)或凭据缓存:
bashgit config --global credential.helper manager-core -
冲突解决:git pull 后冲突 → 手动编辑冲突文件 → git add . → git commit
-
查看某文件历史 :
bashgit log --oneline 文件名
推荐别名(提升效率,添加到全局配置)
bash
git config --global alias.st status
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.cm commit
git config --global alias.ps push
以后就能用 git st、git co 等简写。
这些命令覆盖了 95% 的日常需求!如果你有具体场景(如合并冲突、提交规范、公司 GitLab 流程),告诉我,我可以给你更针对性的命令组合~🚀