Git 常用操作
版本控制常用命令
Git 全局设置
git config --global user.name "Example User"
git config --global user.email "user@example.com" 已有仓库?
cd existing_git_repo
git remote add origin https://github.com/user/repo.git
git push -u origin "master" 创建 git 仓库
mkdir project-name
cd project-name
git init
touch README.md
git add README.md
git commit -m "first commit"
git remote add origin https://github.com/user/repo.git
git push -u origin "master" 常用命令速查
| 命令 | 说明 |
|---|---|
git clone <url> | 克隆远程仓库 |
git status | 查看工作区状态 |
git add . | 暂存所有修改 |
git add <file> | 暂存指定文件 |
git commit -m "msg" | 提交并添加说明 |
git push | 推送到远程 |
git pull | 拉取远程更新 |
git branch | 查看本地分支 |
git branch -a | 查看所有分支 |
git switch -c <branch> | 创建并切换分支 |
git switch <branch> | 切换分支 |
git merge <branch> | 合并指定分支 |
git log --oneline | 简洁查看提交历史 |
git diff | 查看未暂存修改 |
git stash | 暂存当前修改 |
git stash pop | 恢复暂存的修改 |
git reset --soft HEAD~1 | 撤销最近一次提交(保留修改) |
约定式提交常用命令
推荐格式:type(scope): description,其中 scope 可省略。
| 命令 | 说明 |
|---|---|
git commit -m "feat: 新增功能" | 新增功能 |
git commit -m "fix: 修复问题" | 修复缺陷 |
git commit -m "docs: 更新文档" | 仅修改文档 |
git commit -m "style: 调整代码格式" | 不影响逻辑的格式调整 |
git commit -m "refactor: 重构代码" | 既非新增功能也非修复缺陷的重构 |
git commit -m "perf: 优化性能" | 性能优化 |
git commit -m "test: 补充测试" | 新增或修改测试 |
git commit -m "build: 调整构建配置" | 修改构建系统或依赖 |
git commit -m "ci: 更新 CI 配置" | 修改持续集成配置 |
git commit -m "chore: 更新日常任务" | 其他不修改业务代码的维护工作 |
git commit -m "revert: 回退提交" | 撤销之前的提交 |
git commit -m "feat(auth): 增加登录功能" | 使用 scope 标明影响范围 |
Git Worktree 多工作树
同时检出多个分支,无需频繁切换或复制仓库。
| 命令 | 说明 |
|---|---|
git worktree list | 查看所有工作树及其关联分支 |
git worktree add ../<dir> <branch> | 在指定目录检出已有分支 |
git worktree add -b <branch> ../<dir> | 创建新分支并添加工作树 |
git worktree add --detach ../<dir> <commit> | 以分离 HEAD 模式检出指定提交 |
git worktree move ../<old-dir> ../<new-dir> | 移动工作树目录并更新记录 |
git worktree lock ../<dir> | 锁定工作树,防止被自动清理 |
git worktree unlock ../<dir> | 解除工作树锁定 |
git worktree remove ../<dir> | 删除干净的工作树 |
git worktree remove --force ../<dir> | 强制删除含未提交修改的工作树,请谨慎使用 |
git worktree prune | 清理已失效的工作树记录 |