Git 常用命令小結

前言

閱讀本篇文章需要讀者瞭解 Git 的基本用法,如果你對 Git 完全不瞭解,請先行移步瞭解 Git 基礎。
下面是幾份本人覺得不錯的 Git 入門教程,新手可以參考。

創建新分支,並且切換到新分支

> git checkout -b <new_branch_name> # 根據當前所在分支,創建新分支
> git checkout -b <new_branch_name> <remote_name>/<remote_branch_name> # 根據遠程分支,創建分支

切換分支

> git checkout <branch_name>

刪除分支(本地/遠程)

> git branch -d <branch_name> # 刪除本地分支,當該分支沒有關聯遠程分支或者關聯的遠程分支已經合併過,纔會被允許刪除
> git branch -D <branch_name> # 強制刪除本地分支
> git push <remote_name> -d <branch_name> # 刪除遠程分支,git v1.7.0(2010年的版本)之後支持
> git push <remote_name> :<branch_name> # 刪除遠程分支,舊方式,新的也兼容這種

分支重命名

> git branch (-m | -M) [<oldbranch>] <newbranch> # 重命名分支語法,-M 強制重命名,具體參見 git branch --help
> git branch -m <newbranch> # 重命名當前分支
> git branch -m <oldbranch> <newbranch> # 重命名指定分支

重寫 commit 信息

> git rebase -i HEAD~<num> # 交互式地重寫 commit 信息,將會用終端默認的編輯器進行操作

下面的例子中,保存之後,將會使得[328f67b Update Rust]這一條合併到[f55b189 Update cookbook]

pick 164bf1c Update cookbook
pick f55b189 Update cookbook
f 328f67b Update Rust
pick 9834843 Update cookbook

# Rebase 0b6762c..9834843 onto 0b6762c (4 commands)
#
# Commands:
# p, pick = use commit
# r, reword = use commit, but edit the commit message
# e, edit = use commit, but stop for amending
# s, squash = use commit, but meld into previous commit
# f, fixup = like "squash", but discard this commit's log message
# x, exec = run command (the rest of the line) using shell
# d, drop = remove commit
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

注意:最好不要重寫公共的 commit 信息,這會給協作者帶來不必要的困惑,推薦僅僅重寫本地沒有提交的 commit 信息。假設,你非得重寫遠程 commit 信息,請使用 git push -f 來強制更新遠程代碼。

從一個分支摘取 commit 到另一個分支

> git checkout <target-branch> # 切換到目標分支
> git cherry-pick <commit_id> # 將源分支的 commit 摘取到目的分支中

想要切換分支時,發現本地有一些寫了一半的代碼

> git stash # 將當前工作目錄內容儲藏
> git stash --include-untracked # 如果新添加了文件,將其一併儲藏
> git stash pop # 將儲藏的內容恢復到當前分支

回版、撤銷commit

> git reset --hard <commit_id> # 徹底回退到指定 commit

git 回版圖解

丟棄本地新添加的文件

> git clean 

丟棄新的改動

> git checkout . # 注意末尾有個句號

參考資料

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章