Pixiv - KiraraShss
864 字
4 分钟
技术笔记 - 常用Git命令
Git配置相关
- 配置全局用户名和邮箱
git config --global user.name "<Your Name>"git config --global user.email "<your@example.com>"仓库初始化与克隆
- 初始化本地仓库
git init- 克隆远程仓库
git clone <remote-repo-url>- 克隆远程仓库到指定目录
git clone <remote-repo-url> <local-directory>基础工作流
- 查看工作区状态
git status- 添加文件到暂存区
git add <file>- 提交变更
git commit -m "<Commit message>"- 查看提交历史
git log- 查看提交历史(简洁图形化格式)
git log --oneline --graph --decorate --all- 查看所有分支操作记录
git reflog分支管理
- 查看分支
git branch # 查看本地分支git branch -r # 查看远程分支git branch -a # 查看所有分支(本地+远程)- 创建并切换新分支
git checkout -b <new-branch-name>- 切换到已存在分支
git checkout <branch-name>- 合并分支
git merge <branch-name>git merge --no-ff <branch-name> # 禁用Fast Forward合并,保留合并提交- 删除分支
git branch -d <branch-name> # 安全删除已合并分支git branch -D <branch-name> # 强制删除未合并分支- 重命名分支
git branch -m <old-branch-name> <new-branch-name>远程仓库操作
- 查看远程仓库信息
git remote -v- 添加远程仓库
git remote add origin <remote-repo-url>- 推送
git push -u origin <branch-name> # 首次推送需加-u建立关联git push # 后续推送直接使用git push origin <branch-name> # 推送指定分支到远程仓库- 拉取
git pull # 拉取并自动合并(相当于fetch+merge)git fetch origin # 仅拉取不合并(安全)git fetch --prune # 同步远程已删除的分支- 追踪远程分支
git checkout -b local-branch origin/remote-branch撤销与回退
- 工作区撤销(未add)
git checkout -- <filename> # 撤销工作区修改git checkout -- . # 撤销所有未add的变更- 暂存区撤销(已add未commit)
git reset HEAD <filename> # 撤销暂存区修改git reset HEAD . # 撤销所有暂存区修改- 回退版本(已commit未push)
git reset --soft HEAD~<n> # 回退n个版本,保留变更git reset --mixed HEAD~<n> # 默认,回退n个版本并清空暂存区git reset --hard HEAD~<n> # 彻底回退n个版本(危险,会丢失修改)- 回退到指定版本
git reset --hard <commit-hash>- 远程回退(已push)
git revert <commit-hash> # 生成新提交抵消旧提交(保留变更历史,安全)标签管理(版本发布)
- 创建标签
git tag <tag-name> # 当前提交标注标签git tag <tag-name> <commit-hash> # 指定提交标注标签git tag -a <tag-name> -m "<message>" # 创建附注标签(带注释信息)- 查看标签
git tag # 查看所有标签git show <tag-name> # 查看标签详情- 推送标签
git push origin <tag-name> # 推送指定标签到远程仓库git push origin --tags # 推送所有标签到远程仓库- 删除标签
git tag -d <tag-name> # 删除本地标签git push origin --delete <tag-name> # 删除远程标签高阶技巧
- 暂存当前工作
git stash # 暂存当前工作git stash list # 查看stash列表git stash apply # 恢复最近stash(不删除)git stash pop # 恢复并删除最近stashgit stash drop stash@{0} # 删除指定stash- 交互式添加(分块提交)
git add -p # 按块选择要添加的内容- 查看某行代码最后提交者
git blame <filename> -L <line-number>,<line-number>- 查找提交
git log --grep="<关键词>" # 按提交信息搜索git log -S "<代码内容>" # 按代码变动搜索- 清理无效文件
git clean -fd # 删除未跟踪的文件和目录(危险)支持与分享
如果这篇文章对你有帮助,欢迎分享给更多人或赞助支持!
技术笔记 - 常用Git命令
https://blog.xshan.top/posts/git-command/
开拓