Wednesday, September 18, 2024

Common Git Commands

 

# initialize local Git repository

git init

# create the main branch

git checkout -b main

# add local file (eg README.md) to staging

git add README.md

# commit the staging changes with comments (eg first commit)

git commit -m "first commit"

# add a remote repository (Git HTTPS or SSH URL: git@git.abc.com:company-name/Temp_Test_Repo.git)

git remote add origin git@git.abc.com:company-name/Temp_Test_Repo.git

# push the staging changes to the (remote) repository

git push origin main


# create the new branch (eg FY23-01) from main

git checkout -b FY23-01 main

# push the latest changes from the branch (eg FY23-01)

git push origin FY23-01


# revert local commits - for SHA, only need first 5 or 6 characters to differentiate

git revert <new commit SHA>

# undo the above revert

git revert <commit SHA of the previous revert>

# or, make a copy of the original commit

git cherry-pick <original commit SHA>

# check untracked files

git diff

# check local git status for uncommitted files etc

git status

# check git history

git log

# check git history by range

git log --online <start commit SHA>..<end commit SHA>

# cherry-pick multiple commits
git cherry-pick <start commit SHA>..<end commit SHA>


# delete a new local branch (eg FY23-01) in case of recreating
git branch -D FY23-01

# delete a remote branch
git push origin --delete FY23-01


# merge branch FY23-01 back to main

# switch to the target branch (eg main)

git switch main # or git checkout main

# merge from the source branch (eg FY23-01) without fast-forward

git merge --no-ff FY23-01

# push the merged changes back to the target branch (eg main) of the (remote) repository

git push origin main


# rebase from main to the branch created before some updates in main - merged from another branch - later

git switch main

git pull origin main

git switch out-of-date-branch

git rebase main