Git 常用命令的总结

Git 配置和初始化

  1. 设置用户名和邮箱

    1
    2
    git config --global user.name "Your Name"
    git config --global user.email "your.email@example.com"
  2. 查看 Git 配置信息

    1
    git config --list
  3. 初始化一个新的 Git 仓库

    1
    git init
  4. 克隆一个远程仓库

    1
    git clone <repository_url>

文件操作

  1. 查看文件状态

    1
    2
    # 查看当前工作目录的文件状态(是否已修改、是否已添加到暂存区等)。
    git status
  2. 添加文件到暂存区

    1
    git add <file_name>

    或者添加所有文件:

    1
    git add .
  3. 提交更改到本地仓库

    1
    git commit -m "Commit message"
  4. 查看提交历史

    1
    2
    # 查看详细的提交历史记录。
    git log
  5. 查看简洁的提交历史

    1
    2
    # 每个提交只显示一行。
    git log --oneline
  6. 撤销对文件的修改(还原到上次提交的状态)

    1
    git checkout -- <file_name>
  7. 删除文件

    1
    2
    # 删除文件并将删除操作添加到暂存区。
    git rm <file_name>

分支管理

  1. 查看本地分支

    1
    git branch
  2. 创建新分支

    1
    git branch <branch_name>
  3. 切换到其他分支

    1
    git checkout <branch_name>
  4. 创建并切换到新分支

    1
    git checkout -b <branch_name>
  5. 删除本地分支

    1
    git branch -d <branch_name>
  6. 查看所有分支(本地+远程)

    1
    git branch -a
  7. 合并分支

    1
    2
    # 将指定的分支合并到当前分支。
    git merge <branch_name>
  8. 查看合并冲突
    如果在合并时发生冲突,Git 会标记冲突的文件,用户需要手动解决冲突后再进行提交。

远程仓库操作

  1. 查看远程仓库

    1
    git remote -v
  2. 添加远程仓库

    1
    git remote add origin <repository_url>
  3. 推送本地分支到远程仓库

    1
    git push origin <branch_name>
  4. 推送所有本地分支到远程

    1
    git push --all origin
  5. 从远程仓库拉取代码

    1
    git pull origin <branch_name>
  6. 克隆远程仓库

    1
    git clone <repository_url>
  7. 删除远程仓库的分支

    1
    git push origin --delete <branch_name>
  8. 获取远程仓库的最新信息

    1
    git fetch origin

标签管理

  1. 查看所有标签

    1
    git tag
  2. 创建一个新标签

    1
    git tag <tag_name>
  3. 推送标签到远程仓库

    1
    git push origin <tag_name>
  4. 删除本地标签

    1
    git tag -d <tag_name>
  5. 删除远程标签

    1
    git push origin --delete tag <tag_name>

回滚和撤销

  1. 撤销上次提交(保留修改)

    1
    git reset --soft HEAD~1
  2. 撤销上次提交(不保留修改)

    1
    git reset --hard HEAD~1
  3. 撤销文件的暂存

    1
    git reset <file_name>
  4. 重置某个文件的修改(回到上次提交状态)

    1
    git checkout -- <file_name>

其他常用命令

  1. 查看文件差异(尚未提交的文件与上次提交的差异)

    1
    git diff
  2. 显示两个分支或提交之间的差异

    1
    git diff <branch1> <branch2>
  3. 查看文件的提交历史

    1
    git log <file_name>
  4. 忽略文件
    创建 .gitignore 文件,列出要忽略的文件或文件夹。

  5. 使用 stash 暂存未提交的更改

    1
    2
    # 暂存当前更改并清理工作区。
    git stash
  6. 恢复暂存的更改

    1
    git stash pop
  7. 显示远程仓库的详情

    1
    git remote show origin

常见问题解决

  1. 处理合并冲突
    git mergegit pull 时发生冲突,Git 会在冲突的文件中插入标记(<<<<<<<, =======, >>>>>>>),需要手动解决冲突后,标记冲突的文件为已解决,并提交更改。

  2. 查看提交历史并定位问题

    1
    git log --oneline --graph --decorate

Git 常用命令的总结
https://blogs.nover.fun/post/2024/10/Git 常用命令的总结/
作者
Nover
发布于
2024年10月17日
许可协议