企业项目管理、ORK、研发管理与敏捷开发工具平台

网站首页 > 精选文章 正文

Git常用操作

wudianyun 2024-12-16 13:45:44 精选文章 77 ℃

初始化与配置

  • 安装Git
sudo apt-get install git
  • 配置全局用户名和邮箱
git config --global user.name "Your Name" git config --global user.email "your.email@example.com"
  • 生成SSH密钥
ssh-keygen -t rsa -b 4096 -C "your.email@example.com"

然后把生成的公钥配置到服务端对应的用户下

创建仓库

  • 初始化仓库
git init
  • 克隆远程仓库
git clone <remote_url>

提交与修改

  • 添加文件到暂存区
git add <file>
  • 提交暂存区的修改到本地仓库
git commit -m "Commit message"
  • 查看工作区和暂存区的差异
git diff

查看仓库状态和历史

  • 查看仓库状态
git status
  • 查看提交历史
git log

撤销与回退

  • 撤销工作区的修改
git checkout -- <file>
  • 删除文件并从版本库中移除
git rm <file>

分支管理

  • 创建新分支
git branch <branch_name>
  • 切换分支
git checkout <branch_name>
  • 创建临时分支并切换
git checkout -b <new_branch_name>

远程操作

  • 从远程获取代码库
git fetch
  • 下载远程代码并合并
git pull
  • 上传远程代码并合并
git push

使用场景解析

场景1:我刚才提交了什么?

git log -1 HEAD

场景2:我的提交信息写错了

git commit --amend --only -m 'xxxxxxx'

场景3:我想从一个提交里移除一个文件

git checkout HEAD^ myfile
git add -A
git commit --amend

场景4:我想删除我的最后一次提交

git reset HEAD^ --hard
git push -f [remote] [branch]

场景5:如何把本次的修改做提交

  • 添加修改到暂存区
git add .

或者添加特定文件:

git add <file1> <file2>
  • 提交暂存区的修改到本地仓库
git commit -m "Your detailed commit message"
  • 推送到远端
git push origin xxx-release

场景6:推送到多个远程仓库

  1. 添加远程仓库
git remote add <remote-name>  <GitHub仓库URL> 
例如:
git remote add gitlab <GitLab仓库URL>
  1. 推送到特定的远程仓库
git push <remote-name> <branch_name>
例如:
git push origin <branch_name>
  1. 查看远程仓库列表
git remote -v
  1. 管理远程仓库:修改远程仓库URL:
git remote set-url origin <新的GitHub仓库URL> 
git remote set-url gitlab <新的GitLab仓库URL>
  1. 删除远程仓库:
git remote remove gitlab

通过这些步骤,你可以有效地管理你的Git仓库,无论是在本地还是在多个远程仓库之间同步代码。希望这些信息能帮助你更好地使用Git。

Tags:

最近发表
标签列表