[Git] git add 취소하기 , git commit 취소하기, git push 되돌리기

git


git add 취소하기(파일 상태를 Unstage로 변경하기)

  • 아래와 같이 실수로 git add * 명령을 사용하여 모든 파일을 Staging Area에 넣은 경우,
  • Staging Area(git add 명령 수행한 후의 상태)에 넣은 파일을 빼고 싶을 때가 있다.
// 모든 파일이 Staged 상태로 바뀐다.
$ git add *
// 파일들의 상태를 확인한다.
$ git status
On branch master
Changes to be committed:
(use "git reset HEAD <file>..." to unstage)
  renamed:    README.md -> README
  modified:   test.md

이때, git reset HEAD [file] 명령어를 통해 git add를 취소할 수 있다.
뒤에 파일명이 없으면 add한 파일 전체를 취소한다.

// 파일을 Unstage로 변경한다.
$ git reset HEAD test.md
Unstaged changes after reset:
M	test.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:   test.md

git commit 취소하기

완료한 commit을 취소해야 할 때가 있다.

  • 너무 일찍 commit한 경우, 오타가 난 경우
  • 어떤 파일을 빼먹고 commit한 경우 이때, git reset HEAD^ 명령어를 통해 git commit을 취소할 수 있다.
//commit 목록 확인
git log -a

// [방법 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^
HEAD is now at 7df1e85d ~~~~~~

git reset 명령 주의 사항

  • reset 옵션
    • -soft : index 보존(add한 상태, staged 상태), 워킹 디렉토리 파일 보존 , 모두 보존
    • -mixed : index 취소(add 하기 전 상태, unstaged 상태), 워킹 디렉토리 파일 보존( 기본 옵션 )
    • -hard : index 취소(add 하기 전 상태, unstaged 상태), 워킹 디렉토리 파일 삭제, 즉 모두 취소

ex ) 워킹 디렉토리를 원격 저장소의 마지막 commit 상태로 되돌리고 싶으면 ?

단 이 명령을 사용하면 원격 저장소에 있는 마지막 커밋 이후의 워킹 디렉토리와 add 했던 파일들이 모두 사라진다.

git reset --hard HEAD

git push 취소하기

1. 워킹 디렉토리에서 커밋을 되돌린다.

  • 가장 최근의 커밋을 취소하고 워킹 디렉토리를 되돌린다.
git reset HEAD^
  • 원하는 시점으로 워킹 디렉토리를 되돌린다.
git reflog or git log -a
git reset HEAD@{숫자} or git reset [commit id]

2. 되롤려진 상태에서 다시 커밋

git commit -m "blablablablabla"

3. 원격 저장소에 강제로 push

git push origin branch -f
or
git push origin +branch
  • -f 옵션
    • -force 옵션과 동일
  • +branch name
    • 해당 브랜치를 강제로 push 수행

 

개발자 테스트 진행하면서 지라에 커밋해야하는데 가끔 commit 실수를 한다.

매번 찾아보지 말고 블로그에 기록해두고 보도록 하자.

'개발 > Git' 카테고리의 다른 글

Git 화살표 폴더 해결 !  (0) 2021.03.16
git 오류 해결 -1  (0) 2021.01.16
<