[Git] Git 명령어 정리

현용찬·2024년 10월 3일

기존 디렉토리를 git 저장소로 만들기

프로젝트 directory로 가서 git init을 실행하면 새로운 Git 저장소가 만들어짐

코드를 # 프로젝트 directory로 이동
cd [my_project path]

# README 파일 생성
echo "# my_project" >> README.md

# git 저장소로 등록
git init

# 관리할 file을 Staging Area 추가
git add README.md

# Staging Area 에 추가된 파일 commit
git commit -m "first commit"

# 최초 등록된 master branch 대신 main branch 사용하도록 변경
git branch -M main

# 원격 remote repository에 추가
git remote add origin [git URL]

# git push
git push -u origin main

git repository 가져오기

기존에 사용 중인 저장소를 clone 해서 가져올 수 있다.

git clone [url]

git commit

git commit 명령은 Staging Area의 모든 파일을 커밋한다. 저장소에는 하나의 스냅샷으로 기록된다. 그 뒤 현재 Branch가 새 커밋을 가리키게 한다.

git commit -m “[커밋 상세 메시지]”

--amend 옵션으로 최근 커밋을 재작성할 수 있다

git commit --amend

git rm

Staging Area나 Working directory에 있는 파일을 삭제한다.

git rm [file]

git mv

파일/폴더의 이름을 변경한다.

git mv [existing-path] [new-path]

mv 명령어는 사실 아래와 같이 동작한다. 즉 이름이 바뀐 파일을 삭제하고 다시 add 하는 것과 똑같다.

mv README.md README
git rm README.md
git add README

Branch와 Merge

git branch

branch를 관리하는 명령어 이다.

# branch 목록 조회, *가 현재 branch 
git branch

# 원격 branch 목록 조회
git branch -r 

# 전체 branch 목록 조회
git branch -a

branch 를 신규 생성한다.

# branch 생성
git branch [branch-name]

Branch를 변경하고 해당 파일을 Working directory로 복사한다.

# branch checkout
git checkout

git merge

다른 Branch를 현재 Checkout된 Branch에 Merge 한다. Merge 하고 나서 현재 Branch가 Merge 된 결과를 가리키도록 옮긴다.

# 특정 branch를 현재 checkout 된 branch에 merge
git merge [branch]

# remote origin의 main branch merge
git merge origin/main

# local 저장소의 main branch merge
git merge main

git fetch

로컬 저장소에 있는 것을 뺀 remote 저장소의 모든 것을 가져온다.

git fetch [remote]

--prune 옵션으로 remote 저장소에 지워진 브랜치를 local 반영하여 local의 불필요한 branch를 삭제한다.

git fetch --prune

git pull

remote의 commit을 가져오고 병합한다. git fetch 와 git merge 명령을 순서대로 실행하는 것과 같다.

git pull

git push

로컬 저장소의 commit 내역을 remote 저장소로 전송한다.
-u 옵션은 upstream repository를 설정해준다. 즉 한번 설정한 후로는 git push, git pull 만 간단히 쓸 수 있다.

git push [remote] [branch]

git push -u origin main

git remote

원격 저장소 설정 관리 도구다.

#  현재 프로젝트에 등록된 리모트 저장소를 확인
git remote

# 단축이름과 URL을 함께 조회
git remote -v

# git url 에 remote(저장소) 이름으로 등록한다.
git remote add [remote] [url]

git remote add origin https://github.com/cusbert/TIL.git

임시 저장

git stash

현재 작업을 임시 저장하는데 사용한다.

A라는 작업을 진행하다가 잠깐 다른 B 작업을 우선 할 일이 생겼다 이 때 A를 커밋하지 않고 Stash 했다가 B를 끝낸 후 다시 A라는 작업을 진행 할 수 있다. Branch에 상관없이 아직 끝내지 않은 수정사항을 스택에 잠시 임시저장했다가 나중에 다시 적용할 수 있다.

# modified, staged 변경 내용 임시 저장 
git stash

# stashed 조회
git stash list

# stash 내역 working directory로 추가
git stash pop

# stash file 제거
git stash drop

참고

https://wecandev.tistory.com/152

profile
항상 웃어 봅시다

0개의 댓글