Git Cheat Sheet#
See also: Git Cheat Sheet
Setup and Config#
git config: 설정 옵션을 관리한다.- Scope:
--system: 시스템 전체 설정.--global: 사용자별 설정.--local: repository별 설정 (기본값).
- Verb:
list --show-origin: 모든 설정과 해당 설정이 저장된 소스 파일을 표시한다.
- Common Keys:
user.name,user.email: 사용자 식별 정보.core.editor: 기본 텍스트 에디터.init.defaultBranch:git init시 기본 branch 이름.color.ui: 터미널 출력에 색상을 사용한다.alias.<alias-name>: 커스텀 alias를 생성한다 (eg.git config --global alias.co checkout). See gitconfigcredential.helper: 인증 정보를 캐시하거나 저장한다 (eg.cache또는store).
- Scope:
Start a Working Area#
git init: 새로운 Git repository를 초기화한다.git clone <repo> [<dir>]: repository를 새로운 디렉토리에 복제한다.-o <name>: upstream을 추적할 때origin대신<name>을 사용한다.
Work on the Current Change#
git add <path>: 파일 내용을 index에 추가한다.-i, --interactive: 대화형 모드.-p, --patch: 대화형 hunk 선택.
git restore <file>: working tree 파일을 복원한다.--staged: 파일을 unstage한다.-p, --patch: 대화형 hunk 선택.
git rm: working tree와 index에서 파일을 제거한다 (rm <file> && git add <file>과 동일하다).--cached: index에서만 제거한다 (tracking 중지). 실수로 commit된 파일을 제거할 때 유용하다 (eg.git rm --cached .env실행 후.gitignore에.env추가).
git mv <from> <to>: 파일 이동 또는 이름을 변경한다 (mv <from> <to>,git rm <from>,git add <to>와 동일하다).git clean: working tree에서 추적되지 않는(untracked) 파일을 제거한다.-n: 가상 실행 (dry run, 삭제될 파일을 미리 확인).-f: 강제 삭제 (force).-d: 추적되지 않는 디렉토리도 포함하여 삭제한다.-x: 무시된(ignored) 파일도 포함하여 삭제한다 (예: 빌드 결과물).-X: 무시된(ignored) 파일만 삭제한다.
Examine the History and State#
See also: revisions
git status: working tree의 상태를 표시한다.-s, --short: 상태를 간결하게 표시한다 (XY형식:X=staged,Y=WD;A: 추가됨,M: 수정됨,??: 추적되지 않음).
git diff: commit 간, commit과 working tree 간의 변경 사항을 표시한다.- 기본값: working tree vs. index.
--staged,--cached: index vs.HEAD.<commit>: working tree vs.<commit>.--check: 공백 오류(whitespace error)를 검사한다.
git difftool: 외부 diff 도구를 사용하여 변경 사항을 표시한다.git log: commit 로그를 표시한다.-<n>: 최근<n>개의 commit을 표시한다.-- <path>: 특정 파일이나 디렉토리에 관련된 commit만 표시한다.--no-merges: merge commit을 표시하지 않는다.--graph --oneline --all: 히스토리를 시각화하여 표시한다.-p, --patch: 각 commit의 diff를 포함하여 표시한다.--stat: 요약된 통계를 표시한다.-S <string>: 특정 문자열의 발생 횟수가 변경된 commit을 검색한다.
git show [<object>]: 객체(commit, tag, 파일 등)의 상세 정보를 표시한다.git reflog:HEAD와 브랜치 참조가 거쳐간 기록을 표시한다.- reflog를 Git 버전의 shell history라고 생각하면 이해하기 쉽다.
Grow, Mark and Tweak Your Common History#
git commit: repository에 변경 사항을 기록한다.-m <message>: commit 메시지.-a, --all: 모든 tracked 파일의 변경 사항을 stage하고 commit한다.-p, --patch: 대화형 hunk 선택.--amend: 마지막 commit을 새로운 commit으로 대체한다 (메시지 수정 또는 누락된 변경 사항 추가).--no-edit: 에디터를 실행하지 않고 기존 commit 메시지를 그대로 사용한다.
git branch: branch를 관리한다.- No arguments: local branch 목록을 표시한다.
<branch>:HEAD를 기점으로 새로운 branch를 생성한다.-d <branch>: 머지된 branch를 삭제한다.-D <branch>: branch를 강제 삭제한다 (머지되지 않은 branch 삭제 시 필요).-m, --move [<oldbranch>] <newbranch>: branch 이름을 변경한다.-f <branch> <ref>:<branch>를<ref>로 강제 이동시킨다.-u <remotebranch> [<branch>]: upstream을 설정한다 (기본값 현재 branch).--merged [<commit>], --no-merged [<commit>]:<commit>(기본값HEAD) 기준으로 머지 상태에 따라 branch를 필터링한다.
git switch: branch를 전환한다.-c <branch> [<ref>]:<ref>(기본값HEAD)를 가리키는 새로운 branch를 생성하고 전환한다.
git merge <branch>: 둘 이상의 개발 히스토리를 하나로 합친다.--squash: 실제 머지가 발생한 것처럼 작업 디렉토리와 인덱스 상태를 생성하지만, 커밋을 생성하거나HEAD를 이동시키지 않는다.
git mergetool: 외부 병합 도구를 실행하여 충돌을 해결한다 (eg.vimdiff).git rebase <base>: 커밋을 다른 base 끝에 다시 적용한다.-i, --interactive: 대화형 rebase를 수행한다.git rebase <branch1> <branch2>:git checkout <branch2> && git rebase <branch1>과 동일하다.--onto<newbase> <upstream> <branch>: 특정 범위의 commit을 rebase한다.
git cherry-pick <commit>: 기존 commit에 도입된 변경 사항을 적용한다.git reset <ref>: 현재HEAD를 특정 상태로 초기화한다.--hard: WD와 index의 변경 사항을 버린다.-p, --patch: 대화형 hunk 선택.- 비교:
git reset <ref>는HEAD(와 현재 branch)를 이동시키는 반면,git branch -f <branch> <ref>는 일반 branch를 특정 commit으로 강제 이동시킨다.
git stash: 변경 사항을 임시로 보관한다.push가 기본이자 권장되는 서브커맨드다 (과거의save는 deprecated되었다).push(또는git stash단독 실행):-m <msg>: 메시지와 함께 stash를 생성한다.-u, --include-untracked: 추적되지 않는(untracked) 파일도 포함한다.-k, --keep-index: Stash를 생성하지만 index(staged) 상태는 유지한다.-p, --patch: 대화형 hunk 선택.-i, --interactive: 대화형 선택 메뉴.
list: 모든 stash 목록을 표시한다.pop [<stash>]: stash를 적용하고 목록에서 제거한다.--index: Staging area(index) 상태도 함께 복원한다.
apply [<stash>]: stash를 적용하고 목록에 유지한다.--index: Staging area(index) 상태도 함께 복원한다.
drop [<stash>]: stash를 목록에서 제거한다.branch <name> [<stash>]: stash를 기반으로 새로운 branch를 생성하고 해당 stash를 삭제(pop)한다.
git revert <ref>: 기존 commit에 도입된 변경 사항을 되돌리는 새로운 commit을 생성한다.-n, --no-commit: 새로운 commit을 생성하지 않고 변경 사항만 적용한다.git revert <old-ref>..<new-ref>: 특정 범위의 commit을 되돌린다 (<old-ref>는 제외,<new-ref>는 포함).<old-ref>를 포함하려면<old-ref>^..<new-ref>를 사용한다.
git tag <tag> [<commit>]:(기본값 HEAD)을 가리키는 tag를 생성한다.- 기본적으로 lightweight tag를 생성한다.
-a: annotated tag를 생성한다.-l, --list: tag 목록을 표시한다.-d <tag>: tag를 삭제한다.
Collaborate#
git remote: 추적 중인 repository 세트를 관리한다.-v, --verbose: remote의 URL을 표시한다.add <name> <url>: 새로운 remote를 추가한다.rm <name>,remove <name>: remote를 제거한다.show <name>: remote 정보를 표시한다.rename <old> <new>: remote 이름을 변경한다.
git fetch [<remote>] [<src-ref>][:<dst-ref>]: 다른 repository에서 객체와 ref를 다운로드한다.git pull [<remote>] [<refspec>]: 다른 repository나 local branch로부터 데이터를 가져와 통합한다.- 동일한 명령어:
명령어 수동 실행 단계 git pull <remote> <src>git fetch <remote> <src>&&git merge <remote>/<src>git pull --rebase <remote> <src>git fetch <remote> <src>&&git rebase <remote>/<src>git pull <remote> <src>:<dst>git fetch <remote> <src>:<dst>&&git merge FETCH_HEADgit pull --rebase <remote> <src>:<dst>git fetch <remote> <src>:<dst>&&git rebase FETCH_HEAD --rebase: remote에 새로운 commit이 있어git push가 실패할 때 사용한다. local commit들을 가져온 remote commit들 위에 다시 쌓아 fast-forward push가 가능하도록 한다.
- 동일한 명령어:
git push [<remote>] [<src-ref>][:<dst-ref>]: 연관된 객체와 함께 remote ref를 업데이트한다.- 기본 동작: 최신 Git(2.0+)에서 인자 없이
git push를 실행하면 현재 브랜치를 그와 이름이 같은 upstream 브랜치로 push한다. - 전체 Push 옵션:
-a, --all: 모든 브랜치를 push한다.--mirror: 저장소를 미러링한다 (모든 ref push 및 삭제된 ref 반영).
-u, --set-upstream: local branch의 upstream 관계를 설정한다. 브랜치 이름을 생략하면 현재 체크아웃된 브랜치를 대상으로 한다 (eg.git push -u origin). 새로운 브랜치를 처음 push할 때 필수적이다.--delete <branch>: remote branch를 삭제한다.--tags: 모든 local tag를 push한다.
- 기본 동작: 최신 Git(2.0+)에서 인자 없이
- 참고:
git fetch <remote> <src>:<dst>와git push <remote> <src>:<dst>는 완벽히 반대이고,git pull은git fetch에 merge (또는 rebase)를 더한 것이다. git ls-remote <remote>: remote repository의 참조 목록을 표시한다.
Worktree#
git worktree: 여러 working tree를 관리한다.list: worktree 목록을 표시한다.add <path> [-b] <branch>: 새로운 worktree를 추가한다.
Interactive Selection (-p, --patch, -i, --interactive)#
여러 명령어(add, reset, restore, stash push, commit)는 변경 사항을 hunk(파일의 일부) 단위로 선택할 수 있는 “patch” 모드(-p, --patch) 또는 대화형 메뉴(-i, --interactive)를 지원한다.
y: 해당 hunk를 stage/restore/stash 한다.n: 해당 hunk를 stage/restore/stash 하지 않는다.q: 종료한다 (해당 hunk와 남은 모든 hunk를 처리하지 않음).s: 현재 hunk를 더 작은 단위로 나눈다.e: 현재 hunk를 수동으로 편집한다.