Skip to content

Repo setting

Add & init repository

初始化 git repo

$ cd <repo directory> # go into repo directory
$ git init


Check status

查詢當前目錄的 狀態

$ git status
On branch master

Initial commit

nothing to commit

Check commit

$ git log

可以加上--online--graph看到不一樣的輸出格式

$ git log --oneline --graph
  • 找某人的commit
$ git log --oneline --author="Shrely"
  • 找特定commit訊息
$ git log --oneline --grep="wtf"
  • 找commit檔案內容
$ git log -S "Ruby"
  • 找時間區間的commit
$ git log --oneline --since="9am" --until="12am" --after="2017-01"
  • 找特定檔案的commit紀錄
$ git log file.txt

$ git log -p file.txt # -p for more detail information
  • 找特定行的commit message
git blame file.txt

git blame -L 5,10 file.txt # show line 5~10

file operation

增加檔案

將檔案交給git

$ git add welcome.html

$ git add *.html # add all html file into git

git add --allgit add .git 1.x版本有所不同,git add .不會處理刪除檔案的行為,但在git 2.x版本後兩者就相同了

在增加檔案時,可以加入-p再加上e選項,便能在編輯器內編輯想要加入暫存區的區塊

刪除檔案

用系統指令等方式直接刪除

$ rm file.txt
再把修改的刪除檔案狀態 到暫存區

$ git add file.txt

上述動作,也可以用git rm做一次即可

$ git rm file.txt

如果不是真的想刪除檔案,只想把檔案移除git repo內,加入--cached參數即可

$ git rm file.txt --cached

變更檔名

與刪除檔案一樣,直接用git mv完成操作

$ git mv foo.txt bar.txt

忽略檔案

在目錄內新增.gitignore,並把想忽略的檔名輸入進去就好

若要清除已經被忽略的檔案,可以使用git clean

$ git clean -fX

復原檔案

要復原到最後一次的commit,可以使用git checkout

$ git checkout file.txt # file.txt only

$ git checkout . # all file 

也可以復原至前幾次,或指定的commit

$ git checkout HEAD~2 file.txt # 2 commit before current commit


commit message

git commit只會處理暫存區的內容,還沒加到暫存區的檔案,就不會被commit到儲存庫內

可以加入--allow-empty就能在沒東西時也能commit

-a:對已存在repo內的舊檔案進行commit,不需要再add

$ git commit -a -m "updated content"

修改commit訊息

  • --amend:修改最後一次的commit訊息

    $ git commit --amend -m "change last commit" 
    

  • --

追加檔案至最近一次commit

同樣使用--amend參數

$ SSgit add added_file.txt
$ git commit --amend --no-edit

拆除commit

使用git resetreset並不會真的把commit拆除,只是當前工作目錄的狀態改變

$ git reset e12d8ef^ # 拆除到e12d8ef前一次的commit
$ git reset e12d8ef~5 # 拆除到e12d8ef前五次的commit
$ git reset HEAD^ # 拆除HEAD前一次的commit
$ git reset 85e7e30 # 拆除到85e7e30
模式有以下幾種

mixed

--mixed為預設參數,會將暫存區的檔案丟棄,但不會動到工作區的檔案

soft

--soft 都不會丟棄

hard

--hard會將暫存區與工作目錄的檔案全部丟棄

可以利用reflog查看HEAD移動的紀錄

$ git reflog

分支

查看repo分支

$ git branch

.git目錄

git會將檔案及SHA-1值產生Blob物件(Binary large object) 一般看不出來檔案內容,需利用git cat-file查看

$ git cat-file -p <Blob file>

git會對檔案內容使用SHA-1計算,這也是為甚麼一個空的資料夾無法被git感應到