Git 常用命令与高级用法总结
Git 常用命令与高级用法总结
Git 是最流行的分布式版本控制系统,适用于个人和团队协作开发。本文总结了常用命令、回退已 push 代码、git stash 用法及多账号配置方法。
一、Git 常用命令
- 初始化仓库:
1
git init
- 克隆远程仓库:
1
git clone <仓库地址>
- 查看当前状态:
1
git status
- 添加文件到暂存区:
1
git add <文件名>
- 提交更改:
1
git commit -m "提交说明"
- 查看提交历史:
1
git log --oneline --graph --all
- 推送到远程仓库:
1
git push origin <分支名>
- 拉取远程仓库:
1
git pull
- 创建新分支并切换:
1
git checkout -b <新分支名>
- 合并分支:
1
git merge <分支名>
二、回退已 push 到远程仓库的代码
1. 回退到指定提交(强制推送)
- 查看提交历史,找到目标 commit 的哈希值:
1
git log --oneline
- 回退到指定 commit(保留历史,生成新 commit):或者,彻底回退到某次提交(慎用,需强制推送):
1
2git revert <commit_id>
git push origin <分支名>1
2git reset --hard <commit_id>
git push -f origin <分支名>注意:强制推送会覆盖远程分支历史,需团队协作时谨慎操作。
2. 撤销最近一次 push 的 commit
1 | git reset --hard HEAD~1 |
三、git stash 用法总结
- 临时保存当前工作区修改:
1
git stash
- 查看所有 stash:
1
git stash list
- 恢复最近一次 stash 并删除:
1
git stash pop
- 恢复指定 stash:
1
git stash apply stash@{n}
- 删除指定 stash:
1
git stash drop stash@{n}
- 清空所有 stash:
1
git stash clear
四、一台电脑配置多个 GitHub/其他 git 账号的方法
方法一:不同项目使用不同 SSH key
生成多个 SSH key(如个人和公司):
1
2ssh-keygen -t ed25519 -C "[email protected]"
# 按提示保存为 ~/.ssh/id_ed25519_github、~/.ssh/id_ed25519_company 等配置 SSH config 文件:
1
vim ~/.ssh/config
添加如下内容:
1
2
3
4
5
6
7
8
9Host github.com-personal
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_github
Host github.com-company
HostName github.com
User git
IdentityFile ~/.ssh/id_ed25519_company克隆仓库时使用对应 Host:
1
2git clone [email protected]:username/repo.git
git clone [email protected]:company/repo.git
方法二:HTTPS 方式多账号(每次 push 输入账号密码或使用 token)
- 直接用不同账号的 HTTPS 地址即可。
- 推荐配合 Git Credential Manager 管理。
以上内容仅供参考,请结合实际情况具体分析
本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来源 Owen's Blog!