.gitignore 심화 가이드

불필요한 파일을 Git 추적에서 제외하는 패턴과 전략

.gitignore 파일의 패턴 문법, 언어/프레임워크별 템플릿, 이미 추적된 파일 제거 방법, 글로벌 gitignore 설정 등 .gitignore를 효과적으로 활용하는 방법을 상세히 다룬다.

Engineering
Git
DevOps
저자

Kwangmin Kim

공개

2023년 05월 12일

1 .gitignore란?

.gitignore는 Git이 무시할 파일 목록을 정의하는 파일이다. 여기에 등록된 파일은 git add .을 해도 스테이징되지 않는다.

무시해야 하는 파일 유형:

  • 빌드 결과물 (컴파일된 파일, 번들 등)
  • 의존성 디렉토리 (node_modules/, .venv/)
  • 환경 설정 파일 (.env, API 키)
  • IDE 설정 파일 (.vscode/, .idea/)
  • OS 생성 파일 (.DS_Store, Thumbs.db)
  • 로그 파일 (*.log)

2 패턴 문법

2.1 기본 규칙

인라인 주석은 작동하지 않는다

gitignore는 #줄의 첫 글자일 때만 주석으로 인식한다. 줄 중간의 #는 리터럴 문자로 처리된다.

# 올바른 주석 (줄 시작)
/_site/

# 잘못된 인라인 주석 — '/_site/ #설명' 전체가 패턴으로 해석됨
/_site/ #Quarto 렌더링 출력

두 번째 줄은 _site/ 폴더를 무시하지 않는다. /_site/ #Quarto 렌더링 출력이라는 이름의 경로를 무시하는 규칙이 된다. 실제로 이런 이름의 경로는 존재하지 않으므로 아무 효과가 없다.

# 주석 (# 으로 시작하는 줄)
# 빈 줄은 무시됨

# 특정 파일
secret.key
config.local.json

# 특정 확장자
*.log
*.tmp
*.pyc

# 특정 디렉토리 (끝에 / 붙임)
node_modules/
__pycache__/
dist/

# 부정 패턴 (! 로 시작하면 무시하지 않음)
*.log
!important.log   # important.log는 추적함

2.2 와일드카드

패턴 의미 예시
* 슬래시를 제외한 모든 문자 *.log → 모든 .log 파일
** 모든 디렉토리 (0개 이상) **/test/ → 모든 깊이의 test 폴더
? 아무 한 글자 file?.txt → file1.txt, fileA.txt
[abc] a, b, c 중 하나 file[123].txt → file1.txt, file2.txt
[0-9] 범위 내 한 글자 log[0-9].txt → log0.txt ~ log9.txt

2.3 디렉토리 지정

# 루트의 build만 무시 (하위 디렉토리의 build는 추적)
/build

# 모든 위치의 build 디렉토리 무시
build/

# 모든 깊이의 logs 디렉토리 무시
**/logs/

# 특정 경로의 파일만 무시
src/config/local.json

# 특정 디렉토리 아래의 특정 확장자만 무시
docs/**/*.pdf

2.4 패턴 예시

# 디렉토리 안의 모든 파일 무시, 디렉토리 구조는 유지
logs/*
!logs/.gitkeep    # .gitkeep 파일은 유지 (빈 디렉토리 추적 트릭)

# 특정 깊이까지만 무시
src/*/temp/       # src 바로 아래의 모든 폴더 내 temp 디렉토리

# 여러 확장자 무시
*.[oa]            # .o 와 .a 파일
*.py[cod]         # .pyc, .pyo, .pyd 파일

3 언어/프레임워크별 템플릿

3.1 Python

# Byte-compiled
__pycache__/
*.py[cod]
*$py.class

# Virtual environment
.venv/
venv/
env/

# Distribution
dist/
build/
*.egg-info/
*.egg

# IDE
.idea/
.vscode/
*.swp

# Environment
.env
.env.local

# Jupyter Notebook checkpoints
.ipynb_checkpoints/

# pytest
.pytest_cache/
.coverage
htmlcov/

# mypy
.mypy_cache/

3.2 JavaScript / TypeScript

# Dependencies
node_modules/

# Build output
dist/
build/
.next/
out/

# Environment
.env
.env.local
.env.*.local

# IDE
.vscode/
.idea/

# OS
.DS_Store
Thumbs.db

# Debug
npm-debug.log*
yarn-debug.log*
yarn-error.log*

# TypeScript
*.tsbuildinfo

# Testing
coverage/

3.3 Java / Kotlin

# Compiled class files
*.class

# Build
build/
target/
out/

# IDE
.idea/
*.iml
.eclipse/
.settings/

# Gradle
.gradle/
gradle-app.setting

# Maven
*.jar
*.war
*.ear

# Log
*.log
힌트

GitHub에서 제공하는 gitignore 템플릿 저장소에 거의 모든 언어/프레임워크의 .gitignore 템플릿이 있다. 프로젝트 시작 시 참고하면 좋다.

4 이미 추적 중인 파일 무시하기

.gitignore에 추가해도 이미 Git이 추적하고 있는 파일은 계속 추적된다. 추적을 중단하려면 명시적으로 제거해야 한다.

# 파일을 Git 추적에서 제거 (로컬 파일은 유지)
git rm --cached secret.env
rm 'secret.env'
# 디렉토리 전체를 추적에서 제거
git rm -r --cached node_modules/
rm 'node_modules/.package-lock.json'
rm 'node_modules/express/package.json'
rm 'node_modules/express/index.js'
...

파일이 많을수록 rm '...' 줄이 많이 출력된다. --cached 는 로컬 파일을 삭제하지 않고 Git 추적에서만 제거한다.

# .gitignore에 추가
echo "secret.env" >> .gitignore

# 변경사항 커밋
git add .gitignore
git commit -m "chore: Remove tracked files and update .gitignore"
[main 3b2a1c0] chore: Remove tracked files and update .gitignore
 2 files changed, 1 insertion(+)
 delete mode 100644 secret.env

커밋 로그에 delete mode 100644 secret.env 가 나타난다. 이후 .gitignore 에 등록된 파일은 더 이상 추적되지 않는다.

경고

git rm --cached는 로컬 파일을 삭제하지 않지만, 다른 팀원이 git pull을 하면 해당 파일이 삭제될 수 있다. 팀에 미리 공유하고 진행해야 한다.

5 글로벌 .gitignore

모든 Git 저장소에 공통으로 적용되는 gitignore를 설정할 수 있다. OS나 IDE 관련 파일에 적합하다.

# 글로벌 gitignore 파일 생성
git config --global core.excludesFile ~/.gitignore_global

~/.gitignore_global 내용:

# macOS
.DS_Store
.AppleDouble
.LSOverride

# Windows
Thumbs.db
ehthumbs.db
Desktop.ini

# Linux
*~
.directory

# IDE
.idea/
.vscode/
*.swp
*.swo
*~

# Editor backup files
*.bak
*.orig

이렇게 하면 프로젝트별 .gitignore에 OS/IDE 설정을 넣지 않아도 된다.

6 .gitkeep: 빈 디렉토리 추적

Git은 빈 디렉토리를 추적하지 않는다. 빈 디렉토리 구조를 유지하고 싶다면 .gitkeep이라는 빈 파일을 넣는 관례가 있다.

# 빈 디렉토리에 .gitkeep 생성
touch logs/.gitkeep
touch uploads/.gitkeep

# .gitignore에서 디렉토리 내용은 무시하되 .gitkeep은 유지
logs/*
!logs/.gitkeep
노트

.gitkeep은 Git의 공식 기능이 아니라 커뮤니티 관례다. 파일 이름은 아무거나 가능하지만 .gitkeep이 가장 널리 사용된다.

7 디버깅: 왜 파일이 무시되지 않는가?

# 특정 파일이 어떤 .gitignore 규칙에 의해 무시되는지 확인
git check-ignore -v src/config.local.json
.gitignore:5:*.local.json   src/config.local.json

파일:줄번호:매칭된 패턴 형식으로 출력된다. .gitignore 5번째 줄의 *.local.json 패턴에 매칭됐다는 의미이다.

파일이 무시되지 않는다면 (이미 추적 중이거나 규칙이 없는 경우) 아무 출력도 없다:

git check-ignore -v src/app.py
# (아무 출력 없음 → 무시 규칙 없음)

이 경우 git status 에서 해당 파일이 여전히 modified 또는 untracked 로 표시된다. 이미 추적 중이라면 git rm --cached 로 추적에서 제거해야 한다.

8 요약

상황 방법
새 프로젝트 시작 GitHub 템플릿 기반으로 .gitignore 생성
이미 추적 중인 파일 무시 git rm --cached + .gitignore 추가
OS/IDE 파일 무시 글로벌 .gitignore 설정
빈 디렉토리 유지 .gitkeep 파일 추가
규칙 디버깅 git check-ignore -v

Subscribe

Enjoy this blog? Get notified of new posts by email: