손실된 커밋과 브랜치 복구
`git reflog` 및 기타 도구를 사용한 고급 복구 기법을 익혀 손실된 작업과 브랜치를 복원합니다.
손실된 커밋과 브랜치 복구은(는) CoddyKit의 무료 Git Advanced: Monorepo, Submodules & Workflows 강의입니다. 이것은 4개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 Git Advanced: Monorepo, Submodules & Workflows 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. Git Advanced: Monorepo, Submodules & Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.
What Does 'Lost' Mean in Git?
In Git, losing work often means it's just out of immediate reach, not permanently deleted. Git's internal mechanisms keep a detailed history, making recovery possible.
This lesson will equip you with advanced techniques to recover commits, branches, and even fix tricky situations like a detached HEAD.
Reflog: Your Ultimate Safety Net
You might already know git reflog is a powerful tool. It records nearly every change to your HEAD, effectively creating a local history of your repository's state.
Think of it as a journal of where your HEAD pointer has been, even across resets, merges, and checkouts. It's your first stop for recovery.
Decoding Reflog Entries
Each entry in your reflog has a specific format. Understanding it is key to finding what you need:
HEAD@{n}: Indicates the state of HEAD 'n' steps ago.- The commit hash: The actual SHA-1 identifier of the commit.
- The action: A description of what happened (e.g.,
commit,reset,checkout).
By scanning these entries, you can pinpoint the exact commit you wish to recover.
Scenario 1: Recovering a Lost Commit
A common scenario: you accidentally use git reset --hard and lose your latest work. Don't panic! Your commit is still in the reflog.
You can find the commit hash of your 'lost' commit in the reflog and then use git reset --hard to move your current branch's HEAD back to that specific commit.
Example: Resetting to a Reflog Entry
Let's simulate losing a commit and then recovering it. We'll create a commit, 'lose' it with a hard reset, and then use reflog to get it back.
Run these commands in your terminal:
git init
echo "Initial content" > file.txt
git add .
git commit -m "Initial commit"
echo "Second change" >> file.txt
git add .
git commit -m "Second commit (to be lost)"
git reflog # Note the commit hash for "Second commit"
git reset --hard HEAD~1 # This 'loses' the second commit
git reflog # See the reset action
# To recover the 'Second commit', find its hash from the reflog output above.
# For example, if the hash was 'abcdefg':
# git reset --hard abcdefgScenario 2: Resurrecting a Deleted Branch
Accidentally deleted a branch with git branch -D my-feature? Git doesn't immediately destroy the commits; it just removes the pointer.
Use git reflog to find the last commit that your deleted branch pointed to. Once you have the commit hash, you can simply recreate the branch from that point.
git checkout -b feature-a
echo "Work for feature A" > feature.txt
git add .
git commit -m "Working on feature A"
git checkout main
git branch -D feature-a # Uh oh, deleted!
git reflog # Find the commit hash for 'feature-a'
# For example, if the hash was '1234567':
# git branch feature-a 1234567
# git checkout feature-a # Your branch is back!Fixing a Detached HEAD State
A 'detached HEAD' occurs when your HEAD points directly to a commit, not a named branch. Commits made in this state won't be part of any branch unless you explicitly create one.
To fix it, simply create a new branch at your current HEAD position with git branch <new-branch-name>, then switch to it using git checkout <new-branch-name>.
git init
echo "Start" > a.txt
git add .
git commit -m "Initial commit"
git checkout HEAD~1 # This detaches HEAD
echo "New content" > b.txt
git add .
git commit -m "Lost commit in detached state"
# To recover this 'lost' commit:
# git branch my-recovered-work
# git checkout my-recovered-workBeyond Reflog: `git fsck`
For even deeper recovery or integrity checks, git fsck (file system check) is your tool. It verifies the integrity of your Git repository and can find 'dangling' objects that aren't referenced by any ref (branch, tag, or reflog entry).
Using git fsck --lost-found can move these unreferenced objects (commits, blobs) into the .git/lost-found/ directory, giving you a chance to inspect and potentially recover them manually.
git fsck --full --unreachable
# Expected output might look like:
# dangling commit e1f2g3h4i5j6k7l8m9n0o1p2q3r4s5t6u7v8w9x0
# dangling blob a1b2c3d4e5f6g7h8i9j0k1l2m3n4o5p6q7r8s9t0u1Prevention is Key!
While Git offers robust recovery, preventing loss is always better:
- Commit often: Small, frequent commits mean less to lose.
- Push frequently: Remote repositories act as backups.
- Descriptive messages: Helps identify commits in reflog.
- Backup .git: For critical projects, consider backing up the
.gitdirectory itself.
Quick Check: Reflog Recovery
You've accidentally deleted your feature-x branch. Which commands are crucial for finding and restoring its last commit?
Recovery Mastered!
Congratulations! You've mastered advanced Git recovery techniques. You now have the skills to:
- Identify and restore 'lost' commits using
git reflog. - Resurrect accidentally deleted branches.
- Navigate and fix a 'detached HEAD' state.
- Utilize
git fsckfor deeper repository inspection and recovery.
Remember to always push your work to remote repositories regularly as your primary defense against data loss!
자주 묻는 질문
“손실된 커밋과 브랜치 복구” 강의는 무료인가요?
네 — “손실된 커밋과 브랜치 복구” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 Git Advanced: Monorepo, Submodules & Workflows 강의 전체를 잠금 해제할 수 있습니다. Git Advanced: Monorepo, Submodules & Workflows 강의에는 총 4개의 강의가 포함되어 있습니다.
“손실된 커밋과 브랜치 복구”에서 뭘 배우나요?
`git reflog` 및 기타 도구를 사용한 고급 복구 기법을 익혀 손실된 작업과 브랜치를 복원합니다. 브라우저에서 직접 실행하는 실습 코드로 Git Advanced: Monorepo, Submodules & Workflows을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.
Git Advanced: Monorepo, Submodules & Workflows을(를) 시작하는 데 경험이 필요한가요?
사전 경험은 필요하지 않습니다. CoddyKit의 Git Advanced: Monorepo, Submodules & Workflows은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 1번째 강의입니다.
“손실된 커밋과 브랜치 복구” 강의는 얼마나 걸리나요?
대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.
이 Git Advanced: Monorepo, Submodules & Workflows 강의에서 코드를 작성하고 실행할 수 있나요?
네. 모든 Git Advanced: Monorepo, Submodules & Workflows 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.
이 강의의 모든 강의
- 손실된 커밋과 브랜치 복구
- Git Bisect로 디버깅
- Git 저장소 성능 최적화
- Reflog와 Stash로 작업 복구하기