- github에 잘못 올라간 파일을 삭제할 수 있다.
- .gitignore을 설정하지 않고 github remote에 push한 경우, 잘못 올라간 파일을 삭제할 수 있다.
들어가기 전
예를 들어, IntelliJ IDE를 사용할 때 .out 폴더를 .gitignore에 넣지 않고 원격 저장소에 push했다고 가정하자. (IntelliJ의 .out 폴더: 빌드/컴파일 시 .class 파일이 포함된 프로젝트의 출력이 포함되는 위치)
// 모든 파일이 Staged 상태로 바뀐다.
$ git add *
// 파일들의 상태를 확인한다.
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: README.md -> README
modified: CONTRIBUTING.md
이때, git reset HEAD [file] 명령어를 통해 git add를 취소할 수 있다.
// CONTRIBUTING.md 파일을 Unstage로 변경한다.
$ git reset HEAD CONTRIBUTING.md
Unstaged changes after reset:
M CONTRIBUTING.md
// 파일들의 상태를 확인한다.
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
renamed: README.md -> README
Changes not staged for commit:
(use "git add <file>..." to update what will be committed)
(use "git checkout -- <file>..." to discard changes in working directory)
modified: CONTRIBUTING.md
완료한 commit을 취소해야 할 때가 있다.
너무 일찍 commit한 경우
어떤 파일을 빼먹고 commit한 경우 이때, git reset HEAD^ 명령어를 통해 git commit을 취소할 수 있다.
// commit 목록 확인
$ git log
// [방법 1] commit을 취소하고 해당 파일들은 staged 상태로 워킹 디렉터리에 보존
$ git reset --soft HEAD^
// [방법 2] commit을 취소하고 해당 파일들은 unstaged 상태로 워킹 디렉터리에 보존
$ git reset --mixed HEAD^ // 기본 옵션
$ git reset HEAD^ // 위와 동일
$ git reset HEAD~2 // 마지막 2개의 commit을 취소
// [방법 3] commit을 취소하고 해당 파일들은 unstaged 상태로 워킹 디렉터리에서 삭제
$ git reset --hard HEAD^
commit message를 잘못 적은 경우, git commit –amend 명령어를 통해 git commit message를 변경할 수 있다.
$ git commit --amend
TIP git reset 명령은 아래의 옵션과 관련해서 주의하여 사용해야 한다.
TIP 만약 워킹 디렉터리를 원격 저장소의 마지막 commit 상태로 되돌리고 싶으면, 아래의 명령어를 사용한다.
단, 이 명령을 사용하면 원격 저장소에 있는 마지막 commit 이후의 워킹 디렉터리와 add했던 파일들이 모두 사라지므로 주의해야 한다.
// 워킹 디렉터리를 원격 저장소의 마지막 commit 상태로 되돌린다.
$ git reset --hard HEAD
워킹 디렉터리에서 commit 되돌린다.
// 가장 최근의 commit을 취소 (기본 옵션: --mixed)
$ git reset HEAD^
// Reflog(브랜치와 HEAD가 지난 몇 달 동안에 가리켰었던 커밋) 목록 확인
$ git reflog 또는 $ git log -g
// 원하는 시점으로 워킹 디렉터리를 되돌린다.
$ git reset HEAD@{number} 또는 $ git reset [commit id]
되돌려진 상태에서 다시 commit을 한다.
$ git commit -m "Write commit messages"
원격 저장소에 강제로 push 한다.
$ git push origin [branch name] -f
또는
$ git push origin +[branch name]
// Ex) master branch를 원격 저장소(origin)에 강제로 push
$ git push origin +master
TIP 경고를 무시하고 강제로 push 하기
git clean 명령은 추적 중이지 않은 파일만 지우는 게 기본 동작이다. 즉, .gitignore 에 명시하여 무시되는 파일은 지우지 않는다.
$ git clean -f // 디렉터리를 제외한 파일들만 삭제
$ git clean -f -d // 디렉터리까지 삭제
$ git clean -f -d -x // 무시된 파일까지 삭제
TIP option