git基础命令大全

40 阅读2分钟

Git 是一个分布式版本控制系统,广泛用于软件开发和版本管理。以下是一些常用的 Git 命令:

1. 配置工具

  • git config --global user.name "Your Name": 设置提交代码时的用户名。
  • git config --global user.email "email@example.com": 设置提交代码时的邮箱。

2. 创建仓库

  • git init: 在当前目录初始化一个新的Git仓库。
  • git clone <url>: 克隆一个远程仓库到本地。

3. 工作区与暂存区

  • git add <file> 或 git add .: 添加文件或所有更改过的文件到暂存区。
  • git rm <file>: 从暂存区移除文件(也从工作区删除)。
  • git rm --cached <file>: 仅从暂存区移除文件。

4. 查看状态

  • git status: 查看当前分支的修改状态。
  • git diff: 查看尚未暂存的更改。
  • git diff --staged: 查看已暂存但未提交的更改。

5. 提交更改

  • git commit -m "message": 提交暂存区的内容,并添加提交信息。

6. 分支操作

  • git branch: 列出所有本地分支。
  • git branch <branch-name>: 创建新分支。
  • git checkout <branch-name> 或 git switch <branch-name>: 切换分支。
  • git merge <branch>: 合并指定分支到当前分支。
  • git branch -d <branch-name>: 删除本地分支。

7. 远程操作

  • git remote -v: 查看远程仓库信息。
  • git remote add origin <url>: 添加远程仓库。
  • git pull <remote> <branch>: 获取远程更新并合并到当前分支。
  • git push <remote> <branch>: 将本地分支推送到远程仓库。

8. 标签操作

  • git tag: 列出所有标签。
  • git tag <tagname>: 创建标签。
  • git push origin <tagname>: 推送标签到远程。

9. 撤销操作

  • git reset HEAD <file>: 取消暂存文件,但保留工作区的更改。
  • git checkout -- <file>: 弃弃工作区的更改。
  • git revert <commit>: 创建新的提交来撤销旧的提交。

10. 其他命令

  • git log: 显示提交历史。
  • git stash: 暂存当前工作区的状态。
  • git submodule: 管理子模块。

这些是使用 Git 时最常用的一些命令。实际使用中,根据不同的需求还会有更多高级用法和组合。