整理日常开发中最常用的 Git 命令,包含仓库管理、版本回退和服务器配置等场景。
📦 仓库管理
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| # 克隆远程仓库 git clone http://ip:port/xxx/xxx.git
# 拉取最新代码(等同于 fetch + merge) git pull
# 查看所有远程仓库地址 git remote -v
# 添加远程仓库 git remote add origin [url]
# 修改远程地址 git remote set-url origin [url]
# 删除远程仓库 git remote rm origin
|
⚙️ 系统配置
1 2 3 4 5 6 7 8 9 10 11
| # 设置全局HTTP代理 git config --global http.proxy http://127.0.0.1:8080
# 取消代理设置 git config --global --unset http.proxy
# 查看当前代理配置 git config --global --get http.proxy
# 设置用户名 git config --global user.name "your name"
|
⏪ 版本控制
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
| # 强制回退到指定提交(会丢失后续修改!) git reset --hard <commit-hash>
# 强制推送到远程(覆盖远程历史) git push -f
# 查看所有操作记录(包括已删除的commit) git reflog
# 添加待提交文件 git add [files] # 提交到本地仓库 git commit -m "comment" # 推送到远程仓库 git push
|
🌿 分支管理
基础操作
1 2 3 4 5 6 7 8 9 10 11
| # 查看所有分支(含远程分支) git branch -av
# 创建新分支 git branch <branch-name>
# 切换分支 git checkout <branch-name>
# 创建并切换分支(快捷方式) git checkout -b <branch-name>
|
分支同步
1 2 3 4 5
| # 将本地分支与远程关联 git branch --set-upstream-to=origin/<remote-branch> <local-branch>
# 拉取远程分支并立即切换 git checkout -b <local-branch> origin/<remote-branch>
|
分支清理
1 2 3 4 5 6 7 8
| # 删除已合并的分支(安全删除) git branch --merged | grep -v "\*" | xargs -n 1 git branch -d
# 强制删除未合并分支(谨慎!) git branch -D <branch-name>
# 删除远程分支 git push origin --delete <branch-name>
|
分支合并
1 2 3 4 5 6 7 8
| # 普通合并(保留提交历史) git merge <branch-name>
# 变基合并(线性历史) git rebase <base-branch>
# 解决冲突后继续变基 git rebase --continue
|
🔐 GitLab 服务器管理
重置管理员密码(需在GitLab服务器执行)1 2 3 4 5
| gitlab-rails console production user = User.find_by(email: 'admin@example.com') user.password = 'new_password' user.password_confirmation = 'new_password' user.save!
|