Git

Reason is the light and the light of life.

Jerry Su Oct 03, 2018 2 mins

可视化Learn Git Branching

1. 仓库管理

Create Repository

$ mkdir myrepo

$ cd myrepo

$ git init

Initialized empty Git repository in /Users/jerrylsu/myrepo/.git/

Add File to Local Repository

$ git status

$ git diff filename

Check working directory status, and view changes made to the filemname.

$ git add filename

$ git commit -m "write commend"

$ git commit --amend 修改最后一次提交,避免新开一个commit提交到history!

Associated Remote Repo(GitHub)

$ git remote add origin [SSH address]

Note : origin is an alias for the remote repository address.

Push GitHub Repository

$ git push origin branch_name

Now, we can push the latest changes to our local branch to the remote GitHub repository, which is associated above!

2. 分支管理

创建分支

git branch branch_name

切换分支

git checkout branch_name

创建并切换分支

git checkout -b branch_name

查看所有本地分支

$ git branch

合并分支

将其他分支branch_name合并到当前分支

git merge branch_name

将当前分支合并到其他分支branch_name,线性的串接到分支branch_name后

git rebase branch_name

删除本地分支

git branch -d branch_name

删除远程分支

git branch -r -d origin/branch_name

git push origin:branch_name ???

远程新建分支

将本地分支推送到远程不存在的分支,实现远程分支新建

git push origin local_branch:remote_branch

Remove files/dir from git repo

$ git rm --cached file.txt

$ git rm -r --cached dir

$ git commit -m "remove file.txt"

And to push changes to remote repo

$ git push origin branch_name

拉取远程分支

  • 先拉远程master分支:git clone ...

  • 拉取远程分支: git fetch origin remote_branch_name:local_branch_name

  • 查看拉取到本地的分支:git checkout local_branch_name

3. 在提交树上的移动

HEAD 总是指向当前分支上最近一次提交记录。大多数修改提交树的 Git 命令都是从改变 HEAD 的指向开始的。

HEAD 通常情况下是指向分支名的。在你提交时,改变了分支的状态,这一变化通过 HEAD 变得可见。

可以用切换分支的命令来切换到特定一次的提交,提交名是哈希值commit_hash。

git checkout commit_hash(fed2) HEAD分离并指向这个特定的提交

git log获取提交的哈希值,例如fed2da64c0efc5293610bdd892f82a58e8cbc5d8,如果可以唯一标识,取前缀即可fed2。

相对引用

相对引用更方便,使用相对引用可以从一个易于记忆的地方(比如 bugFix 分支或 HEAD)开始计算

  • 使用 ^ 后退1个提交记录,如git checkout main^git checkout main^^,HEAD指向main分支的父节点和父父节点

  • 使用 ~<num> 后退num步提交记录,如 ~3~不接数字等价于^

git checkout fed2    # 分离HEAD指向fed2这次提交

git checkout HEAD^   # HEAD上移

git checkout HEAD^   # HEAD继续上移

强制修改分支位置

git branch -f main HEAD^3/commit_hash

5. 撤销变更

git reset commit_hash

6. 整理提交分支

将commit_hash1与commit_hash2两次提交串接到当前分支下,当前分支指针移动到串接头部commit_hash2。类似于git rebase

git cherry-pick commit_hash1 commit_hash2

4. 恢复本地commit提交

  • 获取commit id: git log

  • 恢复本地commit提交: git reset --hard commit_id

git常用


Read more:

Related posts: