


구조
코드는 아래 세 단계에 걸쳐 저장된다.
스테이징 -> 커밋 -> 원격저장소
git add {파일명} 으로 파일을 스테이징 상태에 넣는다.
git commit 으로 스테이징 상태에 있는 모든 변경사항을 커밋한다. 여기까지가 로컬에서의 작업
git push 로 커밋된 저장소를 원격 저장소로 밀어넣는다.
기본 명령어
저장소 생성
git init
원격 저장소로부터 복제
git clone {url}
변경 사항 체크
git status //
특정 파일 스테이징
git add {파일명}
변경된 모든 파일 스테이징
git add *
커밋
git commit -m “{변경 내용}”
원격으로 보내기
git push origin master
원격저장소 추가
git remote add origin {원격서버주소}
참고 페이지
download(osx): http://code.google.com/p/git-osx-installer/downloads/list
download(windows): http://git-scm.com/download/win
설치 메뉴얼: http://blog.outsider.ne.kr/389
사용 메뉴얼: http://dogfeet.github.io/articles/2012/how-to-github.html
git 간편 안내서: http://rogerdudler.github.com/git-guide/index.ko.html
한장으로 핵심 기능만: http://rogerdudler.github.com/git-guide/files/git_cheat_sheet.pdf
Commit
커밋 합치기
git rebase -i HEAD~4 // 최신 4개의 커밋을 하나로 합치기
커밋 메세지 수정
$ git commit --amend // 마지막 커밋메세지 수정(ref)
간단한 commit방법
$ git add {변경한 파일병}
$ git commit -m “{변경 내용}"
커밋 이력 확인
$ git log // 모든 커밋로그 확인
$ git log -3 // 최근 3개 커밋로그 확인
$ git log --pretty=oneline // 각 커밋을 한 줄로 표시
$ git reflog // reset 혹은 rebase로 없어진 과거의 커밋 이력 확인
커밋 취소
$ git reset HEAD^ // 마지막 커밋 삭제
$ git reset --hard HEAD // 마지막 커밋 상태로 되돌림
$ git reset HEAD * // 스테이징을 언스테이징으로 변경, ref
Branch
master 브랜치를 특정 커밋으로 옮기기
git checkout better_branch
git merge --strategy=ours master # keep the content of this branch, but record a merge
git checkout master
git merge better_branch # fast-forward master up to the merge
브랜치 목록
$ git branch // 로컬
$ git branch -r // 리모트
$ git branch -a // 로컬, 리모트 포함된 모든 브랜치 보기
브랜치 생성
git branch new master // master -> new 브랜치 생성
git push origin new // new 브랜치를 리모트로 보내기
브랜치 삭제
git branch -D {삭제할 브랜치 명} // local
git push origin :{the_remote_branch} // remote
빈 브랜치 생성
$ git checkout --orphan {새로운 브랜치 명}
$ git commit -a // 커밋해야 새로운 브랜치 생성됨
$ git checkout -b new-branch // 브랜치 생성과 동시에 체크아웃
리모트 브랜치 가져오기
$ git checkout -t origin/{가져올 브랜치명} // ref
브랜치 이름 변경
$ git branch -m {new name} // ref
Tag
태그 생성
git tag -a {tag name} -m {tag message} {commit hash}
git tag {tag name} {tag name} -f -m "{new message}" // Edit tag message
태그 삭제
git tag -d {tag name}
git push origin :tags/{tag name} // remote
태그 푸시
git push origin --tags
git push origin {tag name}
git push --tags
기타
파일 삭제
git rm --cached --ignore-unmatch [삭제할 파일명]
히스토리 삭제
목적: 패스워드, 아이디 같은 비공개 정보가 담긴 파일을 실수로 올렸을 때 삭제하는 방법이다. (history에서도 해당 파일만 삭제)
$ git clone [url] # 소스 다운로드
$ cd [foler_name] # 해당 폴더 이동
$ git filter-branch --index-filter 'git rm --cached --ignore-unmatch [삭제할 파일명]' --prune-empty -- --all # 모든 히스토리에서 해당 파일 삭제
$ git push origin master --force # 서버로 전송
히스토리에서 폴더 삭제:
git filter-branch --tree-filter 'rm -rf vendor/gems' HEAD
리모트 주소 추가하여 로컬에 싱크하기
$ git remote add upstream {리모트 주소}
$ git pull upstream {브랜치명}
최적화
$ git gc
$ git gc --aggressive
서버 설정
강제 푸시 설정
git config receive.denynonfastforwards false
Alias
~/.gitconfig 파일을 설정하여 Git 명령어의 앨리어스를 지정할 수 있다.
~/.gitconfig > alias 부분:
[alias]
br = branch
co = checkout
rb = rebase
st = status
cm = commit
pl = pull
ps = push
lg = log --graph --abbrev-commit --decorate --format=format:'%C(cyan)%h%C(reset) - %C(green)(%ar)%C(reset) %C(white)%s%C(reset) %C(dim white)- %an%C(reset)%C(yellow)%d%C(reset)' --all
ad = add
tg = tag
df = diff
■git 한글 매뉴얼
https://git-scm.com/book/ko/v2/
■git config 정리
REM 사용자 이름 및 이메일
git config --global user.name "Your name"
git config --global user.email "Your email address"
REM 설정 조회
git config --global --list
git config --list
REM 출력 색상 활성화
git config --global color.ui "auto"
REM 개행문자 변경 비활성화
git config --global core.autocrlf false
REM SSL 사용 비활성화
git config --global http.sslVerify false
REM 인증서 설정
git config --system http.sslcainfo "C:\PortableApps\cmd_git\mingw32\ssl\certs\ca-bundle.crt"
REM 에디터 설정
git config --global core.editor "'C:\PortableApps\Notepad++Portable\notepad++.exe' -multiInst -nosession"
■github 패스워드 초기화
git credential reject
protocol=https
host=github.com
<엔터>
■github 저장소 초기화
RMDIR /S /Q .git
REM recreate the repos from the current content only
git init
git add .
git commit -m "Initial commit"
REM push to the github remote repos ensuring you overwrite history
git remote add origin "git@github.com:kildong/test.git"
git push -u --force origin master
■git 커맨드 정리
◎git init
로컬저장소 initialize
: .git 폴더가 생긴다. (.git 폴더 없으면 버전관리 되지 않음.)
: 지정한 로컬 저장소가 없으면 새로 생성 + 초기화
git init [로컬저장소위치]
현재 위치 로컬저장소 initialize
git init .
◎git status
현재 상태 확인
: pull 또는 push 할 내용이 있는지 등등 알 수 있다.
git status
◎git diff
바뀐 부분 보기
git diff
◎git add
파일을 Staging Area에 올리기
git add [파일이름]
현재 디렉토리에 있는 모든 파일을 add
git add .
◎git commit
커밋 메시지와 함께 등록
git commit -m "커밋메시지"
add와 commit을 동시에
: 처음 생성한 파일은 추적되지 않는 상태이기 때문에, 최초 한 번은 add 해야 한다.
git commit -am "커밋메시지"
에디터로 커밋 메시지 작성
: 여러 줄의 커밋 메시지를 편하게 작성 가능하다.
git commit
바로 직전 커밋 메시지 수정
1) git commit --amend
2) 에디터로 수정 후 저장
3) git push -f (-f 옵션을 넣어줘야 강제로 덮어 씌워진다. 대신 원격저장소를 내 로컬저장소와 똑같이 만드니까 조심해야한다. 그냥 커밋할 때 조심하자)
◎git log
버전 History 보기 (commit history 확인)
git log
통계 확인 (몇 줄이 추가 되었고, 몇 줄이 삭제되었고)
git log --stat
커밋 메시지, 수정된 부분 함께 보기
git log -p
모든 브랜치 history 보기
git log -all
시각적으로 확인
git log --graph
한 줄로 표시
git log --oneline
포맷팅
git log --pretty=format:"%h -> %an, %ar : %s"
%h: commit id (hash)
%an: author
%ar: 언제 했는지
%s: 메시지
◎git reset
버전 되돌리기 (거의 삭제와 비슷)
: 협업 상태에서 이미 공유된 버전을 reset 하면 안 된다.
git reset
staging area에 있는 파일 내리기
git reset 파일명
이전 커밋 상태로 돌아가기
git reset --hard [commit id]
: --hard => 그 이후 커밋은 모두 없던거로 쳐버리겠다. (커밋 내역 삭제됨.)
: --soft => 해당 커밋으로 되돌아가지만, 그 이후 커밋과 관련된 파일들 (수정되거나 삭제되거나 추가되거나..)은 보존한다.
: 이미 push한 내역에 대해서 reset 한다면, reset 후 push가 안된다. (상태가 완전 달라져버려서) => git push -f하면 원격저장소에도 반영된다.
◎git revert
되돌리기를 포함하면서 되돌린 내용을 보존하는 세련된 친구
: 역순으로 revert 해야 한다.
git revert [revert 될 commit id]
◎git branch
: 기본적으로 Git 저장소를 만들면 자동으로 마스터(master) 브랜치가 생성된다. 이 브랜치는 일반적으로 배포가 가능한 수준의 안정화된 버전을 포함하고 있다.
master branch---develop branch
\---bug fix branch
브랜치 목록 보기
: 현재 브랜치는 * 로 표시
git branch
브랜치 생성
: 현재 브랜치를 기준으로 복사해서 만든다.
git branch [브랜치이름]
브랜치 제거
: 병합이 끝난 브랜치는 제거해주자.
git branch -d [branch]
◎git checkout
브랜치 이동
git checkout [브랜치이름]
원격 저장소의 브랜치를 가져오면서 그 브랜치로 이동
git checkout -b [생성할 브랜치] [가져올 원격브랜치]
not staged 환경에서, 수정된 내용 되돌리기
git checkout -- [file]
◎git merge
브랜치 병합
ex) o2 브랜치를 master 브랜치로 합치겠다.
master 브랜치로 이동
git checkout master
현재 브랜치(master)로 병합하고 싶은 브랜치를 땡겨온다.
git merge o2
병합된 새로운 버전의 커밋 메시지 입력
병합 완료
충돌 해결 후 병합
// 충돌 파일 예시
#Title
content
<<<<<<< HEAD
master
======= (구분자)
o2
>>>>>>> o2
충돌 해결 방법
충돌 해결하고 파일 저장 > git add [충돌파일] > git commit > 충돌 해결 완료
외부 도구를 이용한 병합
: 기존에 셋팅 해두어야 한다.
: ex) p4Merge
git mergetool
커밋 메시지를 남기는 merge
git merge --no-ff <머지할 브랜치>
◎git remote
원격 저장소 목록
git remote
원격 저장소 목록 + 원격 저장소 주소
git remote -v
원격 저장소 상세보기
git remote show [원격저장소이름]
원격 저장소 추가
: 하나의 로컬 저장소를 여러 개의 원격 저장소와 연결 할 수 있기 때문에 원격 저장소에 별명을 붙여준다. (주로 하나의 로컬 저장소에 하나의 원격 저장소를 연결 하기 때문에 origin을 별명으로 많이 쓴다.)
git remote add [원격 저장소 별명] [원격 저장소 주소]
원격 저장소 이름 바꾸기
git remote rename [현재이름] [바꿀이름]
원격 저장소 삭제
git remote rm [원격저장소이름]
◎git push
origin 저장소의 master 브랜치로 push
git push -u origin master
◎git pull
origin 저장소의 master 브랜치 내용 가져오기
git pull origin master
◎git clone
원격 저장소 내용을 로컬 저장소로 복제하기
: 현재 위치로 가져온다.
git clone [원격 저장소]
◎git stash
하던 작업 임시로 저장하기
git stash
stash 목록 확인하기
git stash list
임시 저장 했던 것 다시 적용하기
git stash apply
stash 제거하기
: 적용했지만 목록에는 남아있음. 따라서 제거 해주어야 함.
git stash drop
◎git archive
: git 레파지토리에 있는 소스코드만 압축
git archive --format=zip master -o Master.zip
=> 마스터 브랜치를 zip 형식으로 Master.zip으로 추출
=> .git 폴더는 추출되지 않음.
=> Master.zip 자리에 상대경로 가능 (../Master.zip 이라고 넣으면 상위 디렉토리에 추출됨)
■ID/PW 인증
git clone https://[사용자ID]:[비밀번호]@[git주소]
git clone https://username:password@github.com/username/repository.git
■인증기관 인증서(CA Certificate) 정보 확인
git config --global http.sslCAInfo
■인증기관 인증서(CA Certificate) 위치 지정
git config --global http.sslCAInfo d:/devel/my-ca-bundle.crt
◆이슈:
> git clone https://github.com/theswice/theswice_temp.git
Cloning into 'theswice_temp.git'...
fatal: unable to access 'https://github.com/theswice/theswice_temp.git/':
SSL certificate problem: unable to get local issuer certificate
-->해결 방법:
git config --global http.sslVerify false
또는
export GIT_SSL_NO_VERIFY=0
@ECHO OFF REM ################################################################# REM # REM # 신규 소스코드를 github에 push한다. REM # REM # github에서 repository는 미리 생성되어 있어야 한다. REM # REM ################################################################# REM ======================================= REM ■ CODEPAGE를 UTF-8로 변경 REM ======================================= CHCP 65001 1> NUL 2> NUL SET "CURR_DIR=%CD%" REM ################################################################# REM # REM # 함수 호출 REM # REM ################################################################# CALL :FUNC_GIT_NEWPUSH "d:\0_tmp\src\esecu_utm" "esecu_utm" "esecu_utm" "eSecuVali Corp." CD /D %CURR_DIR% EXIT /B %ERRORLEVEL% REM ################################################################# REM # REM # git을 초기화하고 해당 디렉토리를 모두 push 한다. REM # REM # %1: 소스 디렉토리 REM # %2: branch REM # %3: github remote repository REM # %4: comment REM # REM ################################################################# :FUNC_GIT_NEWPUSH CD /D %1 RMDIR /S /Q .git git init git config --global core.autocrlf false git config pull.rebase true git config credential.helper store --global git config --global http.sslVerify false git config --global user.email "gitest@github.com" git config --global user.name "Hong Kil-Dong" git config --system http.sslcainfo "C:\PortableApps\cmd_git\mingw32\ssl\certs\ca-bundle.crt" git config --global core.editor "'C:\PortableApps\Notepad++Portable\notepad++.exe' -multiInst -nosession" git remote add origin "https://github.com/kildong/%3.git" git add * git commit -m %4 git branch %2 git checkout %2 git pull origin %2 git push --force --set-upstream origin %2 REM git push --set-upstream origin %2 EXIT /B /0