git使用
记录一些git使用命令
# 配置 Git
git config --global user.name "Your Name"
git config --global user.email "your-email@example.com"
# 删除远程分支提交历史
建立一个干净的分支
git checkout --orphan latest_branch
添加文件
git add .
删除master
git branch -D master
重命名当前分支为master
git branch -m master
推送到远程仓库
git push -f origin master
# 记住密码
# 配置凭证存储模式(密码明文保存到 ~/.git-credentials)
git config --global credential.helper store
# 执行一次操作触发凭证保存
git pull
# 取消凭证存储配置
git config --global --unset credential.helper
# 删除凭证文件
rm -f ~/.git-credentials
# 使用 cache 模式(内存缓存,默认 15 分钟)
git config --global credential.helper cache
# 自定义缓存超时时间(秒)
git config --global credential.helper 'cache --timeout=3600'
# 使用用户名密码克隆仓库
# 在 URL 中直接携带用户名和密码克隆(⚠️ 密码会保存在 shell 历史中)
git clone http://username:password@github.com/username/repo.git
说明:
username:password@- 用户名和密码认证github.com:9560- 服务器地址和端口/repo.git- 仓库路径
安全提示:此方式会在命令历史中保存明文密码,建议使用 SSH 密钥或凭证助手代替
# 切换远程分支
# 查看所有远程分支
git branch -r
# 切换到目标分支(如 origin/dev)
git checkout origin/dev # 跟踪远程分支
# 创建并切换到本地分支(与远程分支关联)
git checkout -b business origin/business
说明:
git branch -r- 列出所有远程分支git checkout origin/dev- 直接切换到远程分支(只读模式)git checkout -b business origin/business- 创建本地分支 business 并跟踪远程分支 origin/business(推荐)
# cherry-pick 挑选提交
# 挑选单个提交到当前分支
git cherry-pick <commit-hash>
# 挑选多个提交(按顺序应用)
git cherry-pick <commit-hash-a> <commit-hash-b> <commit-hash-c>
# 挑选多个提交(不包含某个提交)
git cherry-pick <start-commit-hash>..<end-commit-hash>
# 挑选提交但保留原提交信息(不自动创建新提交)
git cherry-pick -n <commit-hash>
# 挑选提交并自动解决冲突(保留当前分支修改)
git cherry-pick -X theirs <commit-hash>
说明:
git cherry-pick- 将指定的提交复制到当前分支<commit-hash>- 提交的 SHA-1 哈希值(可用git log查看)-n(--no-commit) - 只应用更改不自动提交-X theirs- 冲突时优先保留被挑选的提交内容
# 合并多个提交
# 方法一:使用 rebase 合并最近 N 个提交
git rebase -i HEAD~3 # 合并最近 3 个提交
# 方法二:使用 rebase 合并指定范围提交
git rebase -i <commit-hash> # 合并该提交之后的所有提交
# 方法三:软重置后重新提交(将 a,b,c 合并为 all)
git reset --soft HEAD~3 # 撤销最近 3 个提交但保留更改
git commit -m "all" # 重新提交为 all
rebase 交互界面说明:
pick <hash-a> 提交 a
pick <hash-b> 提交 b
pick <hash-c> 提交 c
# 将后两个 pick 改为 s (squash) 或 f (fixup):
pick <hash-a> 提交 a
squash <hash-b> 提交 b
squash <hash-c> 提交 c
说明:
git rebase -i HEAD~3- 交互式变基最近 3 个提交git reset --soft HEAD~3- 软重置,保留所有更改在暂存区squash(s) - 合并提交并保留提交信息fixup(f) - 合并提交并丢弃提交信息
上次更新: 2026/01/16, 08:01:40