Git 常用操作

176 阅读3分钟

基本操作

初始化本地仓库

git init

跟踪文件 | 将改动放入暂存区

# 当前目录下的所有,不包括 .gitignore 中的文件或目录
git add .
# 指定目录
git add { dirName } 
# 指定文件
git add { fileName }
#指定多个文件
git add { fileName1 } { fileName2 }

将改动从暂存区中移除

git restore { fileName }

撤销工作区指定文件的修改

# 还原到最近的 commit 状态
git checkout { fileName }

将暂存区的内容提交到本地仓库

git commit -m '说明文字'

file 查看 commit 日志,提交历史

git log
# 带图像的查看
git log --path

查看工作区当前状态

git status

查看命令历史

git reflog

查看指定文件的改动内容

git diff { fileName }
# 查看工作区指定的文件与版本库中最新的代码有什么区别
git diff HEAD -- { fileName }

回退到之前的 commit

  • tips
    • HEAD 表示当前版本
    • HEAD^ 表示前一版本
    • HEAD^^ 表示前两个版本,依次类推
# 当前的状态不会丢弃
git reset HEAD^

# 丢弃当前的更改
git reset HEAD^ --hard

远程仓库相关

创建本地的 ssh key

ssh-keygen -t rsa -C 'yourEmail@email.com'

本地仓库关联远程仓库

git remote add remoteName address
# remoteName 可以自定义 关联多个远程仓库
# 一些主要的 remote 使用 origin 命名

查看关联的远程仓库

git remote
# 显示远程仓库的地址
git remote -v

删除关联的远程仓库

git remote remove remoteName

重命名关联的远程仓库名称

git remote rename oldRemoteName newRemoteName

将本地分支推向远程仓库

# 全写
git push remoteName localBranchName:remoteBranchName
# 简写 (这种情况一般默认本地与远程分支一致)
git push remoteName branchName
# 例如: git push origin master

克隆远程仓库到本地

git clone remoteAddress

更新本地的分支列表

# 更新所有的远程仓库
git fetch -all
# 更新指定远程仓库,例如 origin
git fetch origin

拉取/合并远程的分支到本地

git pull

分支相关

创建分支

git branch newBranchName

切换分支

git checkout otherBranchName

创建并切换

git checkout -b newBranchName

合并分支

# 快速合并
# 将 otherBranch 合并到当前的分支
git merge otherBranch
# 舍弃合并,尝试恢复到你运行合并前的状态
git merge --abort

删除分支

git branch -d branchName

switch

checkout 既可以切换分支又可以撤销修改,容易造成歧义,所以只想切换分支的话可以使用 switch

# 切换分支
git switch branchName
# 创建并切换
git switch -c newBranchName

stash

将工作区未提交的内容先存储起来

储存

# flagName 用于标示每次的 stash 操作
git stash save flagName

查看现有的 stash 列表

git stash list

恢复存储的内容

# 从列表里取第一个
git stash pop
# 从列表里取指定的
git stash pop stash_id
# or
git stash apply stash_id
# stash_id 通过 git stash list 查看
# 区别
# 1. pop 会在恢复后删除指定的 stash
# 2. apply 不会删除