「Git」:操作技巧

「Git」操作技巧

基本概念

三种状态和三个区

已提交(commited) 已修改(modified) 以暂存(staged)

工作区(working dir) 暂存区(stage area) git 目录(Repo)

基本指令

git clone git push git pull git add git commit git checkout

情景 1:本地新建文件夹写了一些代码想推送到远程仓库

git init
git remote add origin $remote_url
git push -u origin $remote_branch_name

情景 2:想同步到两个 git 仓库

git remote add $name $remote_url2

git push 

时光机

commit id & log

git log --oneline # 显示提交日志,显示 commit id (short)
# 等价于 git log --pretty=oneline --abbrev-commit
git log --pretty=oneline # 显示提交日志,显示 commit id (long)

版本

HEAD 代表当前版本,HEAD^^ (n 个 ^) 或者 HEAD~n,前 n 个版本。

git reset --hard ... 相当于移动 HEAD 指针的位置

在不知道从哪一个点回退时,可以使用 git reflog 显示命令历史

git reset --hard HEAD~2 # 回退到前两个版本
git reset --hard $commit_id # 指定回到哪个版本(这里的 id 写前几位就行)
git reflog # 显示每一次的命令

何谓 stage ?

暂存区

使用 git add 时,就是将文件的修改提交到 暂存区

git diff $id_or_branch -- $file
# 查看工作区和版本库里面文件的区别

git restore $file # 丢弃工作区的改动
git restore --staged $file # 取消暂存 (不改变工作区)

git 的分支

命令:

git branch -a # 列出所有分支
git branch $branch_name # 新建分支
git checkout $branch_name # 切换分支
git checkout -b $b_name # 新建并切换到此分支
git branch -d $b_name # 删除该分支
git merge $b_name # 将该分支合并到当前分支

.gitignore 文件

rebase 是什么

解决冲突

在分支 main 下新建一个分支 dev1 ,修改了某某文件 xxx.xx,在 dev2 分支下同样修改了这个文件,已经将 dev1 merge 到 main 分支上,当 merge dev2 分支时,会发生冲突

此时会进入 MERGING 模式

方法一 —— fast-forward(快进)合并

# 在 MERGING 模式中
nvim xxx.xx # 修改以解决冲突
git add xxx.xx
git commit -m $comment

其他技巧

show top n files

#!/usr/bin/env bash
git rev-list --all | xargs -rL1 git ls-tree -r --long | sort -uk5 | sort -rnk4 | head -${1:10} | awk '{print $1, $2, $3, $4,$5}' | while read -r mode type hash size path; do echo "${mode} ${type} ${hash} $(numfmt --to=iec-i --suffix=B --padding=7 ${size}) ${path}";done

更新 PR 的版本

git clone -b <remote-branch> --single-branch --depth=n <remote git link>
# edit files
git add xxx
git commit -m "xxx"
git rebase -i <first-commit-in3>
# edit some pick to squash
git rebase --continue
git push origin <remote-branch> --force

不再追踪已经提交的某个文件

git update-index --assume-unchanged xxx

协同开发

一些 alias

alias tree = log --online --graph
#git
0%