【git】git常用命令
Git 常用命令速查手册
1. 初始化与克隆
-
初始化仓库
git init -
克隆远程仓库
git clone <repository_url>
2. 配置信息
-
设置全局用户名
git config --global user.name "Your Name" -
设置全局邮箱
git config --global user.email "your.email@example.com" -
查看配置列表
git config --list
3. 添加与提交
-
添加文件到暂存区
git add <file_name>
git add .或git add --all(添加所有修改) -
提交到本地仓库
git commit -m "commit message"
4. 分支管理
-
查看分支
git branch
git branch -a(查看本地+远程分支) -
创建分支
git branch <branch_name> -
切换分支
git checkout <branch_name> -
创建并切换分支
git checkout -b <new_branch_name> -
合并分支
git merge <branch_name>(将指定分支合并到当前分支) -
删除分支
git branch -d <branch_name>(安全删除)
git branch -D <branch_name>(强制删除) -
删除远程分支
git push origin --delete <remote_branch_name>
5. 远程操作
-
关联远程仓库
git remote add origin <repository_url> -
查看远程仓库
git remote -v -
推送分支到远程
git push origin <branch_name>
git push -u origin <branch_name>(首次推送关联上游) -
拉取远程更新
git pull origin <branch_name>(自动合并)
git fetch origin(仅拉取不合并)
6. 状态与历史
-
查看工作区状态
git status -
查看提交历史
git log
git log --oneline --graph(简洁模式+分支图) -
查看某次提交详情
git show <commit_id>
7. 撤销与恢复
-
撤销工作区修改
git restore <file_name> -
撤销暂存区修改
git restore --staged <file_name> -
重置提交记录
git reset --soft HEAD^(保留修改到暂存区)
git reset --hard HEAD^(⚠️ 彻底丢弃修改) -
安全撤销提交
git revert <commit_id>(生成新提交覆盖原修改)
8. 标签管理
-
查看标签
git tag -
创建标签
git tag <tag_name>
git tag -a <tag_name> -m "message"(带注释的标签) -
推送标签到远程
git push origin <tag_name>
git push origin --tags(推送所有本地标签)
9. 其他实用命令
-
暂存修改(临时保存)
git stash
git stash pop(恢复暂存内容) -
比较差异
git diff(工作区 vs 暂存区)
git diff --staged(暂存区 vs 最新提交) -
删除/重命名文件
git rm <file_name>
git mv <old_name> <new_name>
常用场景示例
场景1:首次推送本地代码到远程
git remote add origin https://github.com/user/repo.git
git push -u origin main
场景2:合并分支并解决冲突
git checkout main
git pull origin main # 拉取最新代码
git merge feature-branch # 合并分支
# 手动解决冲突后提交
git add .
git commit -m "Merge feature-branch"
git push origin main

浙公网安备 33010602011771号