前端

[Git]基本命令

2022-05-05  本文已影响0人  是苏菇凉呀

一、git 是什么,用来做什么

git是分布式版本控制系统,用来进行版本管理

二、git 有什么特点

git VS svn

三、git 如何使用

1. 创建版本库

git init

git init 会在当前文件夹下生成一个.git文件夹,也叫做git版本库,用来跟踪管理版本

2. 将本地文件添加到 git 版本库

工作区(Working Directory)

电脑上能看到的目录

版本库(Repository)

工作区中有一个隐藏目录.git,这个不算工作区,而是Git的版本库
Git版本库里存了很多东西,其中最重要的就是暂存区(Stage),还有git自动创建的master分支,以及指向master的指针HEAD

git.png
git status
git add .
git commit -m "commit message"

git add 将文件修改添加到暂存区
git commit 提交更改,将暂存区的所有内容添加到当前分支

3. 添加远程库

git remote add origin git@server-name:path/repo-name.git

必须给远程库一个名字,origin 远程库的名字,也可以设置为其他

将本地库的内容推送到远程

git push -u origin master
git push --set-upstream origin master

-u 将本地 master 分支和远程的 master 分支关联起来

4. 删除远程库

git remote rm origin

此处的 '删除' 其实是解除了本地和远程的绑定关系,并不是物理上删除了远程库

5. 从远程库克隆

git clone git@server-name:path/repo-name.git

git支持多种协议,包括 https/ssh,我们一般都是使用 ssh,因为 https 除了速度慢以外,每次推送都必须输入口令

6. 撤销修改

1)撤销工作区中文件的修改(还未添加到暂存区)

git checkout --file

2) 撤销暂存区中文件的修改(还未提交到远程库)

git reset HEAD file

3)撤销远程库中文件的修改(版本回退)

git log
git reset --hard commit_id
//或者
git revert HEAD //撤销前一次commit
//或者
git reset --hard HEAD^ //回退到上一个版本

HEAD 指向的版本就是当前版本
git log 查看提交历史,以确定回退到哪个版本
git reflog 查看命令历史,以确定回到未来的哪个版本

4)git reset VS git revert

5) 修改最近一次的 commit 提交信息

git commit --amend

输入 i 进入 vim 插入模式,修改完 commit 后, Esc 退出插入模式,:wq 保存退出

7. 分支管理

1) 查看当前分支

git branch

2) 创建分支

git branch <name>

3) 创建+切换分支

git checkout -b <name>
git switch -c <name>

4) 切换分支

git checkout <name>
git switch <name>

5) 合并分支

git merge <branchName>  //合并指定分支到当前分支,并自动创建新的commit提交
git merge --no-commit <branchName>  //合并指定分支到当前分支,但不要进行新的提交

6) 查看分支合并图

git log --graph

7) 删除分支

git branch -d branchA  //删除本地分支
git push origin --delete branchA  //删除远程分支

8. 基本操作

git stash  //将当前工作区存储起来
git stash list  //查看stash list
git stash pop  //恢复工作区
git cherry-pick <commit>  //将提交的commit复制到当前分支,避免重复劳动
git cherry-pick <branch>  //将另一个分支复制到当前分支,避免重复劳动

9. 更新本地代码

1)git fetch

获取远程最新代码到本地,不会进行自动合并

2)git pull

git pull 其实是 git fetchgit merge 的简写,获取远程最新代码到本地,并且和本地分支进行合并操作。

10. 标签管理

标签与 commit 的关系,就像 IP 和域名的关系

1)创建标签

git tag <name>

2)以某个 commit 提交创建标签

git tag <name> commit_id

3)查看创建的所有标签

git tag

4)查看标签信息

git show <tagname>

5)将创建的标签推送到远程

git push origin <tagname>  //推送某个指定的 tag 到远程
git push origin --tags  //推送所有的 tag 到远程

6)删除一个本地标签

git tag -d <tagname>

7)删除一个远程标签

git push origin refes:/tags/<tagname>

四、场景使用

1. 将另一个仓库的某个分支代码复制到当前仓库

git remote add target [target url]      //将目标仓库关联到本地仓库
git fetch target    //拉取目标仓库的代码
git checkout -b new_branch --track target/target_branch   //将目标仓库的某个分支复制到当前仓库对应的分支
上一篇 下一篇

猜你喜欢

热点阅读