Git 版本控制的核心命令——分支、提交、合并以及协作。
配置 Git 并设置您的身份信息
# 设置您的姓名和电子邮件
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"
# 检查您的配置
git config --list
# 设置默认分支名称
git config --global init.defaultBranch main# 设置默认编辑器
git config --global core.editor "code --wait"
# 启用彩色输出
git config --global color.ui auto
# 设置凭据助手(Windows)
git config --global credential.helper wincred初始化或克隆 Git 仓库
# 初始化一个新仓库
git init
# 使用指定分支名称初始化
git init -b main
# 克隆已有仓库
git clone https://github.com/user/repo.git
# 克隆到指定目录
git clone https://github.com/user/repo.git my-folder日常 Git 使用的常用命令
# 检查仓库状态
git status
# 将文件添加到暂存区
git add file.txt
git add . # 添加所有文件
git add *.js # 添加所有 JavaScript 文件
# 提交更改
git commit -m "Commit message"
git commit -am "Message" # 添加并提交已跟踪的文件
# 查看提交历史
git log
git log --oneline # 紧凑视图
git log --graph # 显示分支图创建和管理分支
# 列出分支
git branch # 本地分支
git branch -a # 所有分支(本地 + 远程)
# 创建新分支
git branch feature-branch
# 切换到分支
git checkout feature-branch
git switch feature-branch # 现代替代方案
# 创建并切换到新分支
git checkout -b feature-branch
git switch -c feature-branch# 将分支合并到当前分支
git merge feature-branch
# 删除分支
git branch -d feature-branch # 安全删除
git branch -D feature-branch # 强制删除
# 重命名分支
git branch -m old-name new-name使用远程仓库
# 列出远程仓库
git remote -v
# 添加远程仓库
git remote add origin https://github.com/user/repo.git
# 从远程获取更改
git fetch origin
# 拉取远程更改
git pull origin main
# 推送更改到远程
git push origin main
git push -u origin main # 设置上游并推送# 移除远程
git remote remove origin
# 重命名远程
git remote rename old-name new-name
# 更改远程 URL
git remote set-url origin https://github.com/user/new-repo.git恢复或重置更改
# 丢弃工作目录中的更改
git restore file.txt
git checkout -- file.txt # 旧方式
# 取消暂存文件
git restore --staged file.txt
git reset HEAD file.txt # 旧方式
# 修改最近的提交
git commit --amend -m "New message"
# 还原提交(创建新提交)
git revert <commit-hash># 重置到上一个提交(小心!)
git reset --soft HEAD~1 # 保持更改已暂存
git reset --mixed HEAD~1 # 保持更改未暂存
git reset --hard HEAD~1 # 丢弃所有更改
# 重置到指定提交
git reset --hard <commit-hash>临时保存更改
# 暂存当前更改
git stash
git stash save "Work in progress"
# 列出暂存
git stash list
# 应用暂存
git stash apply # 保留暂存
git stash pop # 应用并移除暂存
# 应用指定的暂存
git stash apply stash@{0}
# 删除暂存
git stash drop stash@{0}
git stash clear # 删除所有暂存检查差异和历史记录
# 显示未暂存的更改
git diff
# 显示已暂存的更改
git diff --staged
git diff --cached
# 显示提交之间的差异
git diff commit1 commit2
# 显示特定文件的更改
git diff file.txt# 显示提交详情
git show <commit-hash>
# 显示特定提交的文件
git show <commit-hash>:file.txt
# 显示文件中谁修改了哪些内容
git blame file.txt其他有用的 Git 命令
# 清理未跟踪的文件
git clean -n # 预演
git clean -f # 删除文件
git clean -fd # 删除文件和目录
# 在仓库中搜索
git grep "search term"
# 显示谁对文件做了更改
git log --follow file.txt
# 创建别名
git config --global alias.st status
git config --global alias.co checkout# 忽略文件更改
git update-index --assume-unchanged file.txt
# 再次跟踪文件更改
git update-index --no-assume-unchanged file.txt
# 显示已跟踪的文件
git ls-files