Git 常用命令速查
一、基础操作
# 初始化仓库
git init
# 克隆仓库
git clone <url>
git clone <url> <目录名> # 指定目录
# 查看状态
git status
git status -s # 简洁输出
二、日常提交
# 添加文件到暂存区
git add <file>
git add . # 添加所有
git add -p # 交互式分段添加
# 提交
git commit -m "message"
git commit -am "message" # 跳过暂存,直接提交已跟踪文件
# 修改最近提交
git commit --amend -m "new message"
git commit --amend --no-edit # 不改信息
三、分支操作
# 查看分支
git branch # 本地
git branch -r # 远程
git branch -a # 全部
# 创建/切换
git branch <name>
git checkout -b <name> # 创建并切换
git switch -c <name> # 新版写法
# 删除
git branch -d <name> # 已合并
git branch -D <name> # 强制删除
# 合并
git merge <branch>
git merge --no-ff <branch> # 保留分支历史
四、远程操作
# 查看远程
git remote -v
git remote add origin <url>
# 推送
git push origin <branch>
git push -u origin <branch> # 设置上游
git push --all # 推送所有分支
git push origin --delete <branch> # 删除远程分支
# 拉取
git pull # = fetch + merge
git pull --rebase # = fetch + rebase
git fetch origin # 只拉取不合并
五、撤销与回滚
# 工作区撤销
git checkout -- <file> # 丢弃工作区修改
git restore <file> # 新版
# 暂存区撤销
git reset HEAD <file> # 取消暂存
git restore --staged <file> # 新版
# 回滚提交
git reset --soft HEAD~1 # 保留工作区和暂存区
git reset --mixed HEAD~1 # 保留工作区,清空暂存区
git reset --hard HEAD~1 # 全部丢弃,慎用
# 回滚到指定版本
git reset --hard <commit-hash>
# 安全回滚(生成新提交)
git revert <commit-hash>
六、日志与比较
# 查看日志
git log
git log --oneline --graph # 简洁图形化
git log --author="name" # 按作者
git log --since="2024-01-01" # 按时间
# 比较差异
git diff # 工作区 vs 暂存区
git diff --cached # 暂存区 vs 上次提交
git diff HEAD # 工作区 vs 上次提交
git diff <branch1> <branch2> # 分支间差异
七、stash 临时存储
git stash # 暂存修改
git stash list # 查看列表
git stash pop # 恢复并删除
git stash apply # 恢复但不删除
git stash drop # 删除指定
git stash clear # 清空所有
八、实用技巧
# 配置别名
git config --global alias.co checkout
git config --global alias.br branch
git config --global alias.ci commit
git config --global alias.st status
# 配置用户信息
git config --global user.name "Your Name"
git config --global user.email "your@email.com"
# 忽略文件权限变化
git config core.fileMode false
# 查看某行代码是谁写的
git blame <file>
# 清理未跟踪文件
git clean -fd # 删除未跟踪文件和目录
git clean -nd # 预览将要删除的文件
九、常见问题
# 误操作恢复
git reflog # 查看所有操作记录
git reset --hard HEAD@{n} # 恢复到某个操作前
# 合并冲突后放弃
git merge --abort
# 修改远程仓库地址
git remote set-url origin <new-url>
# 子模块
git submodule update --init --recursive
记住:--hard 要慎重,reflog 是你的后悔药。
💻 安全运维 / Linux运维 / 渗透测试 技术支持
业务需求可联系博客作者
