git常用操作

1/11/2020 #git

Add & Commit

将文件添加到暂存:

git add <file>

暂存所有文件:

git add .

将所有暂存文件提交到 git,并显示一条消息:

git commit -m "Message goes here"

提交对跟踪文件所做的所有更改并提交:

git commit -am "Message Goes Here"

Branch

添加 -r 标志以显示所有删除分支。为所有分支添加 -a 标志:

git branch

创建新分支:

git branch <branch-name>

切换到新分支并更新工作目录:

git checkout <branch>

创建一个新分支并切换到该分支:

git checkout -b <new-branch>

删除合并的分支:

git branch -d <branch>

删除分支,无论是合并的还是现在的:

git branch -D <branch>

向当前提交添加标记(通常用于新版本版本):

git tag <tag-name>

Merge

将分支 a 合并到分支 b 中:

git checkout b
git merge a

将所有提交合并并压缩为一个新提交:

git merge -- squash a

Rebase

将feature分支重新定位到main(以合并对 main 所做的新更改)。防止不必要的合并提交到功能中,保持历史记录整洁:

git checkout feature
git rebase main

在将主数据库重新定位之前,以交互方式清理分支的提交:

git rebase -i main

以交互方式将最后 3 个提交重新基于当前分支:

git rebase -i Head~3

撤消操作

移动/改名:

git mv <existing_path> <new_path>

从工作目录和暂存区域中删除文件,然后暂存删除:

git rm <file>

仅从暂存区域中删除:

git rm --cached <file>

查看以前的提交(只读):

git checkout <commit_ID>

创建一个新提交,还原指定提交的更改:

git revert <commit_ID>

返回到之前的提交并删除之前的所有提交(还原更安全)。添加 --硬标志以同时删除工作区更改(非常小心):

git reset <commit_ID>

列出提交历史记录,以及相应的 ID:

git log --online

显示对未暂存文件的更改,添加 --cached 选项:

git diff

显示两个提交之间的更改:

git diff commit1_ID commit2_ID

Stash

存储已修改和暂存的更改。要包括未跟踪的文件,请添加 -u 标志。对于未跟踪和忽略的文件,请添加 -a 标志:

git stash

如上,但添加注释:

git stash save "comment"

Partial。仅存储文件中的单个更改:

git stash -p

列出所有stash:

git stash list

重新应用stash而不删除它:

git stash apply

在索引 2 处重新应用stash,然后将其从列表中删除。省略 stash@(n) 以删除最新的stash:

git stash pop stash@(2)

显示stash 1 的差异。 加-p开关查看全部差异:

git stash show stash@(1)

删除索引 1 处的stash。省略 stash@(n) 以删除上次stash:

git stash drop stash@(1)

删除所有stash:

git stash clear

远程操作

添加远程repo:

git remote add <alias> <url>

查看所有远程连接。添加 -v 标志以查看网址:

git remote

重命名连接:

git remote rename <old> <new>

从远程repo中获取所有分支(无合并):

git fetch <alias>

获取特定分支:

git fetch <alias> <branch>

获取当前分支的远程repo副本,然后合并:

git pull

将本地更改移动到对远程repo所做的新更改的顶部(用于干净、线性的历史记录):

git pull --rebase <alias>

将本地内容上传到远程repo:

git push <alias>

上传到分支(然后可以拉取请求):

git push <alias> <branch>