Git Step-2 : Git 기초

1. Git 저장소 만들기

  • 기존 프로젝트 디렉토리를 Git 저장소로 만들기

    $cd project_path
    $git init
    

    git init명령어는 project_path에 .git 디렉토리라는 저장소에 필요한 뼈대 파일을 생성합니다.

    $cd project_path/.git
    $ls 또는 dir
      
    config   #해당 프로젝트에만 적용되는 설정 옵션
    objects/ #모든 컨텐트를 저장하는 데이터베이스
    refs/    #디렉토리에는 커밋 개체의 포인터(브랜치, 태그, 리모트 등)를 저장
    HEAD     #현재 Checkout한 브랜치 정보
    index    #Staging Area의 정보를 저장
    info/
    logs/
    hooks/ 
    COMMIT_EDITMSG
    description
    FETCH_HEAD
    ORIG_HEAD
    packed-refs
      
    
  • 기존 저장소를 Clone하기

    다른 프로젝트에 참여하려거나(Contribute) Git 저장소를 복사하고 싶을때 git clone <url> 명령어를 사용합니다. url은 Git Server의 Https 정보입니다. Github를 사용한다면 복사하고 싶은 Github 페이지로 접속하여 그림에 나와 있는 https://정보를 복사하여 git clone 명령어를 실행하면 됩니다.

    image-20210223141336591

    git clone으로 해당 프로젝트를 로컬로 복사할때 프로젝트 디렉토리명을 지정하고 싶다면 맨 뒤에 이름을 지정하면 됩니다.

    $git clone https://github.com/microsoft/vscode-remote-release.git myProjectName
    

    git clone은 다양한 프로토콜을 지원합니다. https:// 뿐만 아니라 git://, SSH, github에서 제공하는 CLI를 이용하면 gh clone 명령어로 복사도 가능합니다.

2. 파일 상태

Git은 Working Directory Staging Area Git Repository 3가지 섹션으로 구분됩니다. 그 중 Working Directory에 존재하는 tracked(관리대상)파일과 untracked(신규 파일)파일이 존재하며, tracked 파일은 이전에 commit을 하여 스냅샷으로 저장되었거나 stated 된 파일입니다. tracked 파일은 최초에 unmodified 상태였다가 수정을 하면 modified 상태가 됩니다. 그 후 git add 명령어를 실행하게 되면 modified, untracked 파일들이 Staging Area로 이동하게 됩니다.

image-20210223143828115

3. 파일 상태 확인

Git 저장소에 first.txt 파일을 하나 생성하고 git status 명령을 실행합니다.

$git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        first.txt

nothing added to commit but untracked files present (use "git add" to track)

위 내용을 살펴보면 master branch에 commit 되지 않은 Untracked 상태의 first.txt가 있으니 git add하라고 나옵니다.

git의 모든 명령어는 옵션이 있고 git [명령어] [옵션] 형태로 사용할 수 있습니다. status에 유용하게 사용할 수 있는 옵션은 -s입니다. 파일의 상태를 간결하게 표시해 줍니다.

$git status -s
 M first.txt

$git status -s
MM second.txt
A  third.txt

파일 앞에 붙는 문자는 파일의 상태를 함축적으로 표현하는 문자입니다.

XY PATH
XY ORIG_PATH -> PATH

X shows the status of the index and Y shows the status of the working tree.

'' = unmodified
M = modified
A = added
D = deleted
R = renamed
C = copied
U = updated but unmerged

X          Y     Meaning
-------------------------------------------------
         [AMD]   not updated
M        [ MD]   updated in index
A        [ MD]   added to index
D                deleted from index
R        [ MD]   renamed in index
C        [ MD]   copied in index
[MARC]           index and work tree matches
[ MARC]     M    work tree changed since index
[ MARC]     D    deleted in work tree
[ D]        R    renamed in work tree
[ D]        C    copied in work tree
-------------------------------------------------
D           D    unmerged, both deleted
A           U    unmerged, added by us
U           D    unmerged, deleted by them
U           A    unmerged, added by them
D           U    unmerged, deleted by us
A           A    unmerged, both added
U           U    unmerged, both modified
-------------------------------------------------
?           ?    untracked
!           !    ignored
-------------------------------------------------

자세한 옵션을 알고 싶다면 git status -h 또는 git help status 명령을 실행 하시면 됩니다.

4. git add 명령어

git add 명령은 파일을 새로 추적하거나 수정한 파일을 Staged 상태로 만들 때 사용합니다. 또한 Merge 할 때 충돌난 상태의 파일을 Resolve 상태로 만들때도 사용하기도 합니다. add의 의미를 staged 한다기 보다는 다음 커밋에 추가한다고 받아들이는게 좋습니다.

git add뒤에 파일명을 적어주거나 . 또는 *.확장자 등을 붙여주지 않으면 오류가 발생합니다.

$git add
Nothing specified, nothing added.
hint: Maybe you wanted to say 'git add .'?
hint: Turn this message off by running
hint: "git config advice.addEmptyPathspec false"

git add 명령으로 Working Directory에 untracked된 first.txt을 Staging Area로 이동시킨 후

git status 명령으로 파일 상태를 보면 staged 상태가 되었습니다. (Changes to be committed에 들어 있는 파일은 staged 상태라는 것을 의미)

$git add .
$git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   first.txt

git rm --cached 명령어로 Staging Area에서 다시 Working Directory로 돌려 보낼 수 있습니다.

$git rm --cached *.txt
rm 'first.txt'

$git status
On branch master

No commits yet

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        first.txt

nothing added to commit but untracked files present (use "git add" to track)

git restore --staged 라는 명령어로도 동일한 결과를 만들 수 있습니다.

$git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        new file:   first.txt

$git restore --staged .
$git status
On branch master

Untracked files:
  (use "git add <file>..." to include in what will be committed)
        first.txt.txt

no changes added to commit (use "git add" and/or "git commit -a")

두 명령어의 차이점은 git restore --staged 명령어는 Staging Area에서만 Working Direcotry로 지정된 파일을 옮기지만 git rm --cached 또는 git rm -r --cached명령어에서 지정된 파일들은 Repository에서 삭제되고, Staging Area에는 deleted 상태로, Working directory는 untracked 상태로 만듭니다.

만약 신규 git 저장소에 1.txt를 생성하고 staged 시킨 다음 두 명령어를 실행 시킨다면 동일한 결과가 나올 것이며, 다른 조건이라면 다른 결과가 나올 것입니다. 순수하게 unstaged가 목적이라면서 git restore --staged 명령어를 사용해야 되고, commit 되어 tracked된 파일을 .gitignore에서 관리해야 된다면 git rm --cached 명령어를 사용하고 deleted 상태로 staged된 파일을 commit 해야 됩니다.

한가지 주목해야 할 점은 first.txt파일이 working directory에서 untracked 상태였다가 Staging Area로 stated된 다음 tracked 상태에서 git rm --chached 명령을 실행 하면서 다시 untracked 상태로 돌아온 것입니다. 즉 Staging Area로 간다고 해서 영구적으로 tracked 상태가 아니라 commit으로 스냅샷이 Git Directory에 저장된 시점부터 영구적으로 tracked 상태가 된다는 점입니다.

다시 first.txt 파일을 git add하고 staged 상태인 first.txt파일을 수정하면 어떻게 될까요?

파일의 상태는 Staged, Unstaged 2개가 됩니다.

$git status
On branch master

No commits yet

Changes to be committed:
  (use "git rm --cached <file>..." to unstage)
        new file:   first.txt

Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   first.txt

git add 명령을 실행하게 되면 first.txt 파일을 Staging Area로 이동하는데 이때 Git이 미리 commit 될 데이터를 생성해 두기 때문입니다. 따라서 이 상태에서 commit을 하게 된다면 수정된 first.txt파일이 아닌 이전에 git add 명령을 실행한 first.txt파일이 Repository에 저장되게 되고, 수정된 first.txt 파일은 아직 Working Directory에 남아 있게 됩니다. 만약 수정된 내용을 포함하여 commit 하기를 원한다면 git add를 다시 한 후에 commit을 하시면 됩니다.

$git commit -m "first.txt commit"
[master (root-commit) baf6d20] first.txt commit
 1 file changed, 0 insertions(+), 0 deletions(-)
 create mode 100644 first.txt

$git status
On branch master
Changes not staged for commit:
  (use "git add <file>..." to update what will be committed)
  (use "git restore <file>..." to discard changes in working directory)
        modified:   first.txt

no changes added to commit (use "git add" and/or "git commit -a")

5. git commit 명령어

git commit 명령은 staged 된 파일들을 local repository에 저장(스냅샷하여 저장)하는 역할을 수행합니다.

커밋(스냅샷) 된 파일들은 영구적으로 tracked 상태가 되고, commit 후에는 Working Directory에 unmodifeid된 상태가 됩니다. Unstaged 상태인 파일들은 commit되지 않습니다.

$git status -s
M  first.txt
A  second.txt
?? third.txt

$git commit -m "test commit"
[master 8c1a19c] test commit
 2 files changed, 2 insertions(+)
 create mode 100644 second.txt

$git status -s
?? third.txt

Staging Area 생략 후 바로 commit 하는 옵션도 -a 를 사용할 수도 있습니다.

$git commit -a -m "direct commit"

6. .gitignore 파일

.gitignore 파일에 제외 시킬 파일들의 리스트 작성하면 Git은 해당 파일들을 tracked(관리대상)으로 지정하지 않습니다.

이미 tracked된 파일의 경우 .gitignore에 등록 하여도 Git이 상태 변화를 체크합니다.

.gitignore 파일은 보통 처음에 만들어 두는 것이 편리하며 그래서 Git 저장소에 커밋하고 싶지 않은 파일을 실수로 커밋하는 일을 방지할 수 있습니다.

패턴 규칙

아무것도 없는 라인이나, #로 시작하는 라인은 무시한다.

표준 Glob 패턴을 사용한다. 이는 프로젝트 전체에 적용된다.

슬래시(/)로 시작하면 하위 디렉토리에 적용되지(Recursivity) 않는다.

디렉토리는 슬래시(/)를 끝에 사용하는 것으로 표현한다.

느낌표(!)로 시작하는 패턴의 파일은 무시하지 않는다.

Glob 패턴은 정규표현식을 단순하게 만든 것으로 생각하면 되고 보통 쉘에서 많이 사용합니다.

.gitignore를 사용하는 간단한 방식은 하나의 .gitignore 파일을 최상위 디렉토리에 하나 두고 모든 하위 디렉토리에까지 적용시키는 방식입니다. 물론 .gitignore 파일을 하나만 두는 것이 아니라 하위 디렉토리에도 추가로 둘 수도 있습니다. .gitignore 정책은 현재 .gitignore 파일이 위치한 디렉토리와 그 하위 디렉토리에 적용됩니다.

# Vim
*~
*.sw[p_]

# Sublime Text
*.sublime-project
*.sublime-workspace

# Ruby Gem
*.gem
.bundle
Gemfile.lock
**/vendor/bundle

7. git diff 명령어

git diff 명령어는 Working Directory와 Staging Area의 파일 내용을 비교합니다.

$git status -s
A  diff.txt
$echo "\n add line " >> diff.txt
$git status -s
AM  diff.txt
$git diff

image-20210224012906395

위 라인에서 + 녹색으로 표시된 부분이 추가된 부분이며, 라인을 수정하거나 삭제한다면 - 빨간색으로 표시 해줍니다.

만약 이전 commit된 파일과 staged된 파일을 비교하고 싶다면 git diff --staged 명령어를 쓰면 됩니다.

git diff 대신 git difftool 명령을 사용해서 emerge, vimdiff 같은 도구로 비교할 수 있으며 상용 제품도 사용할 수 있습니다. git difftool --tool-help 라는 명령은 사용가능한 도구를 보여줍니다.

8. git mv, rm 명령어

git mv는 파일 이름이나 경로를 변경할 때 사용하며, git rm은 파일 삭제 또는 cached 삭제를 할 수 있습니다.

$git mv test.txt new.txt
$ git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        renamed:    test.txt -> new.txt
 
$git commit -m "test1"
...

$git rm c.txt
rm 'c.txt'

$git status
On branch master
Changes to be committed:
  (use "git restore --staged <file>..." to unstage)
        deleted:    c.txt

$git commit -m "delete file"
[master 7b67070] delete file
 1 file changed, 9 deletions(-)
 delete mode 100644 c.txt
 
$git status
On branch master
nothing to commit, working tree clean

9. git log 명령어

git log 명령을 실행하면 저장소의 커밋 히스토리를 최근 커밋 시간순으로 보입니다. 각 로그는 커밋의 SHA-1 체크섬, 저자 이름, 저자 이메일, 커밋한 날짜, 커밋 메시지를 표시합니다.

commit 0a564e9e0a503434261192a1582c62270c3d6727 (HEAD -> master)
Author: donghyeok-dev <donghyeok.jh@gmail.com>
Date:   Thu Feb 25 11:51:55 2021 +0900

    second commit

commit b5e7d22022390a11c99ce7e8a09545e6d0cbfa12
Author: donghyeok-dev <donghyeok.jh@gmail.com>
Date:   Thu Feb 25 11:49:34 2021 +0900

    first commit

다시 터미널로 돌아갈려면 q를 누르면 됩니다.

  • SYNOPSIS

    git log [<options>] [revision range] [--] < ...]
    
  • OPTIONS

    --oneline

    커밋된 로그 정보를 간략하게 보여줍니다. 그래서 hash 값도 전체값이 아닌 축소값으로 보이고 빠져 있는 정보들도 있습니다.

    $git log --oneline
    f8ce154 (HEAD -> master) azz
    a0b80d1 tt
    b5be55f test file rename to test2
    ebf0e23 test file update -2
    82f9e3a test file update - 1
    95fa202 ^ third commit
    0a564e9 second commit
    b5e7d22 first commit
    

    --pretty

    기본 형식 이외에 특정 정보를 얻기 위해 사용합니다.

    git log --pretty=format 에 쓸 몇가지 유용한 옵션` 포맷에서 사용하는 유용한 옵션을 참고하세요.

    아래는 사용 예제입니다.

    $git log --pretty=oneline
      
    7b67070a38861e1e8dc7bda3d019fa0aa4a1bc10 (HEAD -> master) delete file
    b8e4363ed819b3eb2f6c21e2905afec2bd9f2093 aaa
    cd32b6d4f1eafd7d99cc29aace302e50c26f308f aa
      
    $git log --pretty=short
      
    commit 7b67070a38861e1e8dc7bda3d019fa0aa4a1bc10 (HEAD -> master)
    Author: donghyeok <donghyeok.jh@gmail.com>
      
        delete file
      
    commit b8e4363ed819b3eb2f6c21e2905afec2bd9f2093
    Author: donghyeok <donghyeok.jh@gmail.com>
      
        aaa
      
      
    $git log --pretty=full
      
    commit 7b67070a38861e1e8dc7bda3d019fa0aa4a1bc10 (HEAD -> master)
    Author: donghyeok <donghyeok.jh@gmail.com>
    Commit: donghyeok <donghyeok.jh@gmail.com>
      
        delete file
      
    commit b8e4363ed819b3eb2f6c21e2905afec2bd9f2093
    Author: donghyeok <donghyeok.jh@gmail.com>
    Commit: donghyeok <donghyeok.jh@gmail.com>
      
        aaa
      
      
    $git log --pretty=fuller
    commit 7b67070a38861e1e8dc7bda3d019fa0aa4a1bc10 (HEAD -> master)
    Author:     donghyeok <donghyeok.jh@gmail.com>
    AuthorDate: Wed Feb 24 02:18:30 2021 +0900
    Commit:     donghyeok <donghyeok.jh@gmail.com>
    CommitDate: Wed Feb 24 02:18:30 2021 +0900
      
        delete file
      
    commit b8e4363ed819b3eb2f6c21e2905afec2bd9f2093
    Author:     donghyeok <donghyeok.jh@gmail.com>
    AuthorDate: Wed Feb 24 02:14:18 2021 +0900
    Commit:     donghyeok <donghyeok.jh@gmail.com>
    CommitDate: Wed Feb 24 02:14:18 2021 +0900
      
        aaa
          
    $git log --pretty=format:"%h - %an, %ar : %s"
    7b67070 - donghyeok, 2 days ago : delete file
    b8e4363 - donghyeok, 2 days ago : aaa
    cd32b6d - donghyeok, 2 days ago : aa
    

    -p (--patch) -[count]

    최근커밋의 count 수 만큼 diff 결과를 보여줍니다. 이 옵션은 직접 diff를 실행한 것과 같은 결과를 출력하기 때문에 동료가 무엇을 커밋했는지 리뷰하고 빨리 조회하는데 유용합니다.

    $git log --oneline -p -2
    f8ce154 (HEAD -> master) azz
    diff --git a/second.txt b/second.txt
    index 7c4a013..a22fb06 100644
    --- a/second.txt
    +++ b/second.txt
    @@ -1 +1,2 @@
    -aaa
    \ No newline at end of file
    +aaa
    +bb
    \ No newline at end of file
    a0b80d1 tt
    diff --git a/third.txt b/third.txt
    index e132db2..1d1d082 100644
    --- a/third.txt
    +++ b/third.txt
    @@ -1 +1,2 @@
    

    --stat

    파일의 변경, 내용의 추가 삭제의 통계를 보여줍니다.

    $git log --oneline --stat
    f8ce154 (HEAD -> master) azz
     second.txt | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    a0b80d1 tt
     third.txt | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    b5be55f test file rename to test2
     test.txt => test2.txt | 0
     1 file changed, 0 insertions(+), 0 deletions(-)
    ebf0e23 test file update -2
     test.txt | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    82f9e3a test file update - 1
     test.txt | 3 ++-
     1 file changed, 2 insertions(+), 1 deletion(-)
    95fa202 ^ third commit
     third.txt | 1 +
    

    --follow

    하나의 파일의 history를 보여줍니다.

    파일이름이 변경되기 전 history도 포함하여 보여줍니다.

    git log test2.txt 는 현재 파일에 대한 history만 보입니다.

    $git log --follow test2.txt
    

    --decorate[=short|full|auto|no]

    커밋의 참조 이름을 표시합니다.

    #기본정보 표시
    $git log --decorate
    commit ca82a6dff817ec66f44342007202690a93763949 (HEAD -> master, origin/master, origin/HEAD)
      
    ##전체정보 표시
    $git log --decorate=full
    commit ca82a6dff817ec66f44342007202690a93763949 (HEAD -> refs/heads/master, refs/remotes/origin/master, refs/remotes/origin/HEAD)
      
    #ref name prefixes refs/heads,refs/tags,refs/remotes 표시안함
    $git log --decorate=short  
    commit ca82a6dff817ec66f44342007202690a93763949 (HEAD -> master, origin/master, origin/HEAD)
      
    #참조값 표시 안함
    $git log --decorate=no    //--no-decorate와 동일하게 작동하며 참조 이름을 표시하지 않습니다.
    commit ca82a6dff817ec66f44342007202690a93763949
    
  • git log 주요 옵션

    • -p (--patch) 각 커밋에 diff 결과가 적용된 패치를 보여준다.

    • --stat 각 거밋에서 수정된 파일의 통계정보를 보여준다.

    • --shortstat –stat 명령의 결과 중에서 수정한 파일, 추가된 라인, 삭제된 라인만 보여준다.

    • --name-only 커밋 정보중에서 수정된 파일의 목록만 보여준다.

    • --name-status 수정된 파일의 목록을 보여줄 뿐만 아니라 파일의 상태도 보여준다.

      acd94fb0 post update
      M       assets/css/main.scss
      A       assets/images/posts/image-20210223141336591.png
      
    • --abbrev-commit 40자 짜리 SHA-1 체크섬을 전부 보여주는 것이 아니라 처음 몇 자만 보여준다.

    • --relative-date 정확한 시간을 보여주는 것이 아니라 “2 weeks ago”처럼 상대적인 형식으로 보여준다.
    • --graph 브랜치와 머지 히스토리 정보까지 아스키 그래프로 보여준다.
    • --pretty 지정한 형식으로 보여준다. oneline, short, full, fuller, format의 부가 옵션이 있다.
    • --oneline –pretty=oneline –abbrev-commit 두 옵션을 함께 사용한 것과 같음.
  • 조회 제한조건

    -n, --since, --until 등 시간을 기준으로 조회 하는 옵션은 매우 유용합니다.

    지난 2주 동안 만들어진 커밋들만 조회 하는 명령

    $git log --oneline --since=2.weeks --author=donghyeok-dev --pretty=format:"%cd %an : %s" --
    e-only
      
    Fri Feb 26 17:52:27 2021 +0900 donghyeok-dev : post update
    temp_post/2021-02-26-BirtReport-1.md
    temp_post/birt_1.PNG
    temp_post/birt_2.PNG
      
    Fri Feb 26 11:28:24 2021 +0900 donghyeok-dev : post dev-1 modify
    _posts/tools/2021-02-22-development tools-1.md
    assets/images/posts/image-20210222055630154.png
    assets/images/posts/image-20210222061631389.png
    assets/images/posts/image-20210222062336485.png
    assets/images/posts/image-20210226111630406.png
    

    --author--grep 옵션을 함께 사용하여 모두 만족하는 커밋을 찾으려면 --all-match 옵션도 반드시 함께 사용해야 됩니다.

    • -(n) 최근 n개의 커밋만 조회한다.
    • --since, --after 명시한 날짜 이후의 커밋만 검색한다.
    • --until, --before 명시한 날짜 이전의 커밋만 조회한다.
    • --author 입력한 저자의 커밋만 보여준다.
    • --committer 입력한 커미터의 커밋만 보여준다.
    • --grep 커밋 메시지 안의 텍스를 검색한다.
    • -S 커밋 변경(추가/삭제) 내용 안의 텍스트를 검색한다.

    • --no-merges 검색결과에서 머지 커밋을 표시하지 않도록 한다.
  • 좋은 git 커밋 메시지를 작성하기 위한 방법입니다.

    • 제목과 본문을 한 줄 띄워 분리하기

    • 제목은 영문 기준 50자 이내로

    • 제목 첫글자는 대문자로

    • 제목 끝에 . 금지

    • 제목은 명령조로

    • 본문은 영문 기준 72자마다 줄 바꾸기

    • 본문은 어떻게 보다 무엇을, 왜에 맞춰 작성하기

      (출처: https://meetup.toast.com/posts/106 )

      –oneline으로 볼 때 제목 줄 바꿈시 제목만 보입니다.

      commit 메시지를 입력할 때 git commit -m " 제목 엔터 "는 모두 작성 후에 닫고 엔터로 저장합니다.

      $git log
      commit 51b4119d5bd926b4583570b04c6aa2a0afcbbc7a (HEAD -> master)
      Author: donghyeok <donghyeok.jh@gmail.com>
      Date:   Mon Mar 1 01:13:58 2021 +0900
          
          Test Commit Message2 hello world
          
      commit 7c67b17154cba9346f20e46bef26bccd21ab4ffd
      Author: donghyeok <donghyeok.jh@gmail.com>
      Date:   Mon Mar 1 01:12:40 2021 +0900
          
          Test Commit Message!
          
          hello world
            
      $git log --oneline    
      51b4119d (HEAD -> master) Test Commit Message2 hello world
      7c67b171 Test Commit Message!
      

10. 원복하기

  • --amend 명령어는 Commit에 누락된 내용을 추가할 때 사용합니다.

    $git commit -m "commit message"
    $git log --oneline --name-only
    64cbe8f (HEAD -> master) commit message
    diff.txt
      
    $git add new.txt
    $git commit -amend
      
    //editor와 연결되어있다면 edit창에 아래 내용이 보이고 편집할 수 있음.
      
    change commit message
      
    ggg
      
    # Please enter the commit message for your changes. Lines starting
    # with '#' will be ignored, and an empty message aborts the commit.
    #
    # Date:      Mon Mar 1 10:28:39 2021 +0900
    #
    # On branch master
    # Changes to be committed:
    #	modified:   diff.txt
    

    --amend 옵션으로 커밋을 고치는 작업은 이전의 커밋을 완전히 새로 고쳐서 새 커밋으로 변경하는 것이기 때문에 이전의 커밋은 히스토리에 남지 않습니다.

    --amend 옵션으로 커밋을 고치는 작업이 주는 장점은 마지막 커밋 작업에서 아주 살짝 뭔가 빠뜨린 것을 넣거나 변경하는 것을 새 커밋으로 분리하지 않고 하나의 커밋에서 처리하는 것입니다. “앗차, 빠진 파일 넣었음”, “이전 커밋에서 오타 살짝 고침” 등의 커밋을 만들지 않아도 될 것 입니다.

  • Untracted 상태로 변경하기

    git rm --cached [file] 명령으로 commit된 파일을 untracked 상태로 변경할 수 있습니다.

    $git rm --cached new.txt
    rm 'new.txt'
      
    $git status -s
    D  new.txt
    ?? new.txt
      
    $git commit -m "Remove new.txt in repository"
    [master 3b67c7b] Remove new.txt in repository
     1 file changed, 2 deletions(-)
     delete mode 100644 new.txt
       
    $git status -s
    ?? new.txt
    
  • UnStaged 상태로 변경하기

    git restore --staged [file] 또는 git reset [file]으로 unstaged할 수 있습니다.

  • 최근 커밋된 버전으로 원복하기

    git checkout -- [file]

11. 리모트 저장소

리모트 저장소는 인터넷이나 네트워크 어딘가에 있는 저장소를 말합니다. 저장소는 여러개가 있을 수 있는데 어떤 저장소는 일고 쓰기 모두 할 수 있고 어떤 저장소는 읽기만 가능할 수 있습니다. 다른 사람들과 함께 협업한다는 것은 리모트 저장소를 관리하면서 데이터를 거기에 Push, Pull 하거나 저장소를 추가, 삭제 하는 것 뿐만 아니라 브랜치를 관리하고 추적할지 말지 등을 관리하는 것을 말합니다.

  • 리모트 저장소 확인하기

    git remote명령으로 현재 프로젝트에 등록된 리모트 저장소의 단축이름을 확인할 수 있습니다. 저장소를 clone하면 ‘origin’ 이라는 리모트 저장소가 자동으로 등록되기 때문에 ‘origin’ 이라는 이름을 볼 수 있습니다.

    $git remote
    origin
    

    -v 옵션을 주면 단축이름과 URL을 함께 볼 수 있습니다.

    $git remote -v
    origin  https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (fetch)
    origin  https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (push)
    
  • 리모트 저장소 추가하기

    git remote add <단축이름> <url> 명령으로 기존 Working Directory에서 새 리모트 저장소를 쉽게 추가할 수 있습니다.

    $git remote add ts https://github.com/donghyeok-dev/donghyeok-dev.github.io.git
      
    $git remote add pb https://github.com/paulboone/ticgit
      
    $git remote -v
    pb      https://github.com/paulboone/ticgit (fetch)
    pb      https://github.com/paulboone/ticgit (push)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (fetch)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (push)
    

    이제 url대신 단축이름을 사용할 수 있으며 pb의 저장소에 있는 것을 가져오려면 아래와 같이 실행합니다.

    $git fetch pb
    remote: Enumerating objects: 634, done.
    remote: Total 634 (delta 0), reused 0 (delta 0), pack-reused 634
    Receiving objects: 100% (634/634), 88.93 KiB | 347.00 KiB/s, done.
    Resolving deltas: 100% (261/261), done.
    From https://github.com/paulboone/ticgit
     * [new branch]      master     -> pb/master
     * [new branch]      ticgit     -> pb/ticgit
    

    로컬에서 pb/master가 pb의 master 브랜치이며 이 브랜치를 로컬 브랜치 중 하나에 Merge하거나 Checkout 해서 브랜치 내용을 자세히 확인할 수 있습니다.

  • 리모트 저장소 데이터 가져오기

    git fetch <remote> 명령은 로컬에는 없지만 리모트 저장소에 있는 데이터를 모두 가져옵니다. 단 자동으로 Merge 하지 않기 때문에 수동으로 Merge해야 합니다.

    git pull 명령으로 리모트 저장소 브랜치에서 데이터를 가져올 뿐만 아니라 자동으로 로컬 브랜치와 Merge 시킬 수 있습니다.

  • 리모트 저장소 이름 바꾸거나 삭제하기

    git remote rename <기존 단축이름=""> <변경할 단축이름=""> 명령으로 저장소의 이름을 변경할 수 있습니다.

    $git remote -v
    pb      https://github.com/paulboone/ticgit (fetch)
    pb      https://github.com/paulboone/ticgit (push)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (fetch)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (push)
      
    $git remote rename pb npb
      
    $git remote -v
    npb     https://github.com/paulboone/ticgit (fetch)
    npb     https://github.com/paulboone/ticgit (push)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (fetch)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (push)
    

    리모트 저장소 이름을 변경하면 리모트 저장소의 브랜치 이름도 변경됩니다. pb/master에서 npb/master로 변경됩니다.

    git remote rm <단축이름> 명령으로 리모트 저장소를 삭제할 수 있으며 삭제 후에는 리모트 저장소에 관련된 추적 브랜치 정보나 모든 설정 내용도 함께 삭제됩니다.

    $git remote rm npb
    $git remote -v
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (fetch)
    ts      https://github.com/donghyeok-dev/donghyeok-dev.github.io.git (push)
    

12. Tag

git tag 명령으로 tag를 조회할 수 있고, -l, –list 옵션으로 태그를 조회할 수도 있습니다.

Tag는 Lightweight와 Annotated 두 종류가 있습니다.

  • Annotated Tag

    Tag를 만든 사람 이름, 이메일과 만든 날짜, Tag 메시지를 저장하며 GPG(GNU Privacy Guard)로 서명할 수 도 있습니다.

    $git tag -a 1.0.0 -m "version 1.0.0"
    $git tag
    1.0.0
      
    $git show 1.0.0
    tag 1.0.0
    Tagger: donghyeok <donghyeok.jh@gmail.com>
    Date:   Mon Mar 1 21:09:22 2021 +0900
      
    version 1.0.0
      
    commit 0edef4c781779e232206821ef2778e15e6a46891 (HEAD -> master, tag: 1.0.0)
    Author: donghyeok <donghyeok.jh@gmail.com>
    Date:   Mon Mar 1 16:58:57 2021 +0900
      
        2
      
    diff --git a/new.txt b/new.txt
    deleted file mode 100644
    index 3e23e0d..0000000
    --- a/new.txt
    +++ /dev/null
    @@ -1,2 +0,0 @@
    -1111
    -222a
    
  • Lightweight Tag

    파일에 커밋 체크섬을 저장할뿐 다른 정보는 저장하지 않습니다. 또한 Lightweight Tag를 만들 때는 -a, -s, -m 옵션을 사용하지 않습니다.

    $git tag 1.0.1w
    $git show 1.0.1w
    commit 0edef4c781779e232206821ef2778e15e6a46891 (HEAD -> master, tag: 1.0.1w, tag: 1.0.0)
    Author: donghyeok <donghyeok.jh@gmail.com>
    Date:   Mon Mar 1 16:58:57 2021 +0900
      
        2
      
    diff --git a/new.txt b/new.txt
    deleted file mode 100644
    index 3e23e0d..0000000
    --- a/new.txt
    +++ /dev/null
    @@ -1,2 +0,0 @@
    -1111
    -222a
    
  • 이전 커밋에 Tag 붙이기

    $git log --pretty=oneline
    0edef4c781779e232206821ef2778e15e6a46891 (HEAD -> master, tag: 1.0.1w, tag: 1.0.0) 27b75c05661b0313c553f8249cbbddfca2d413801 1
    3b67c7bec846f621e7c3c8a184905dc8f63b5a55 Remove new.txt in repository
    f77de070e7a3c9f551187bf05a76545d9a6f6cd5 change commit message2
    7b67070a38861e1e8dc7bda3d019fa0aa4a1bc10 delete file
    b8e4363ed819b3eb2f6c21e2905afec2bd9f2093 aaa
    cd32b6d4f1eafd7d99cc29aace302e50c26f308f aa
    fae894444f131234c1241a2832b91430c60678d6 g
    

    체크섬을 사용할때는 체크섬의 앞 7자리만 명시하면 됩니다.

    $git tag -a 1.0.2 f77de07
      
    $git tag -l
    1.0.0
    1.0.1w
    1.0.2
      
    $git show 1.0.2
    tag 1.0.2
    Tagger: donghyeok <donghyeok.jh@gmail.com>
    Date:   Mon Mar 1 21:26:35 2021 +0900
      
    Append tag message
      
    commit f77de070e7a3c9f551187bf05a76545d9a6f6cd5 (tag: 1.0.2)
    Author: donghyeok <donghyeok.jh@gmail.com>
    Date:   Mon Mar 1 10:28:39 2021 +0900
      
        change commit message2
      
        ggg
      
    diff --git a/diff.txt b/diff.txt
    index d45694b..6bd1b01 100644
    --- a/diff.txt
    +++ b/diff.txt
    @@ -1,7 +1,7 @@
     diff initial 1
     diff initial 2
     diff initial 3add line
    
  • tag 공유하기

    git push 명령은 자동으로 리모트 서버에 태그를 전송하지 않습니다. git push origin <Tag Name>을 실행 해야 합니다. 만약 한번에 여러 개의 Tag를 서버로 Push하고 싶다면 –tags 옵션을 추가하여 실행합니다.

    $git push origin 1.0.1
      
    $git push origin --tags
    

    특정 tag를 checkout 받아서 파일들을 확인할 수 도 있습니다.

    $git checkout 2.0.0
    

13. Git Alias

각종 명령어들을 Alias로 줄여 사용할 수 있습니다. 앞에 !를 추가하면 외부 명령을 실행합니다.

$git config --global alias.co checkout
$git config --global alias.br branch
$git config --global alias.ci commit
$git config --global alias.st status

$git config --global alias.unstage 'reset HEAD --'
$git config --global alias.last 'log -1 HEAD'

$git config --global alias.visual '!gitk'

댓글남기기