홈 › Git › 01 / 8

저장소와 커밋

섹션 7진행 0 / 8

3. 코드 예제

예제 1: 저장소 초기화와 status 읽기 — 01_repo_commit.sh 발췌

bash
git init -q -b main
git config core.autocrlf false
git config color.ui false
git status

cat > Main.java <<'EOF'
public class Main {
    public static void main(String[] args) {
        System.out.println("hello");
    }
}
EOF
git status -s
text
On branch main

No commits yet

nothing to commit (create/copy files and use "git add" to track)
?? Main.java
?? pom.xml

빈 저장소는 "No commits yet" 로 표시됩니다. Main.java, pom.xml 을 만들면 둘 다 ?? 로 나와 아직 추적하지 않는 새 파일임을 보여줍니다.

예제 2: 첫 커밋과 log — 01_repo_commit.sh 발췌

bash
git add Main.java pom.xml
git status -s
git commit -m "초기 커밋: Main 클래스와 pom.xml 추가"
git log --oneline
text
A  Main.java
A  pom.xml
[main (root-commit) bd1717e] 초기 커밋: Main 클래스와 pom.xml 추가
 2 files changed, 11 insertions(+)
 create mode 100644 Main.java
 create mode 100644 pom.xml
bd1717e 초기 커밋: Main 클래스와 pom.xml 추가

add 후 A 기호로 스테이징된 상태를 확인하고 commit 합니다. --oneline 은 해시와 메시지 한 줄만 보여줍니다.

예제 3: 작업 트리·스테이징·HEAD 3방향 diff — 01_repo_commit.sh 발췌

bash
sed -i 's/hello/hello, git/' Main.java
git add Main.java
sed -i 's/hello, git/hello, git!/' Main.java
git diff              # 작업 트리 vs 스테이징
git diff --staged     # 스테이징 vs HEAD
text
diff --git a/Main.java b/Main.java
index 5e28bc3..cfd3c1f 100644
--- a/Main.java
+++ b/Main.java
@@ -1,5 +1,5 @@
 public class Main {
     public static void main(String[] args) {
-        System.out.println("hello, git");
+        System.out.println("hello, git!");
     }
 }
diff --git a/Main.java b/Main.java
index b8e3fe9..5e28bc3 100644
--- a/Main.java
+++ b/Main.java
@@ -1,5 +1,5 @@
 public class Main {
     public static void main(String[] args) {
-        System.out.println("hello");
+        System.out.println("hello, git");
     }
 }

한 파일을 두 번 고쳤습니다. 먼저 hello 를 hello, git 으로 바꿔 add 했고, 다시 hello, git! 으로 고쳤습니다. git diff 는 add 이후 변경(git → git!)만, --staged 는 add 한 변경(hello → git)만 보여줍니다. 둘을 합친 전체 변경은 git diff HEAD 로 보며, 표 2.8 을 참고하세요.

예제 4: .gitignore 로 추적 중이던 파일 빼기 — 01_repo_commit.sh 발췌

bash
# target/Main.class 와 app.log 는 이미 커밋된 상태
cat > .gitignore <<'EOF'
target/
build/
*.class
*.log
.idea/
*.iml
EOF
git status -s
git rm -r --cached target app.log -q
git status -s
text
?? .gitignore
D  app.log
D  target/Main.class
?? .gitignore

빌드 산출물과 로그를 실수로 커밋한 뒤 상황입니다. .gitignore 를 추가해도 이미 추적 중인 두 파일은 그대로 남아, git rm --cached 로 추적만 뺀 뒤에야 D 로 스테이징됩니다.