Basic Operations
git clone <repository-url> # Clone a repository
git add .
git commit -m 'description' # Stage and commit changes
git pull # Fetch and merge remote changes
git pull --rebase # Pull with rebase instead of merge
git checkout main # Switch to main branch
git checkout a1b2c3d4 # Checkout specific commit by hash
git merge develop # Merge develop branch into current branch
git push # Push commits to remote
git push origin HEAD:refs/for/main # Push for code review
Creating a Local Branch and Pushing to Remote
git branch feature-auth-module # Create local branch
git checkout feature-auth-module # Switch to new branch
git merge main # Optional: merge from main
git add .
git commit -m 'fix(): add local branch'
git push --set-upstream origin feature-auth-module # Push and set upstream
git pull # Fetch latest remote changes
Deleting Branches
git branch --delete develop # Delete local branch
git push origin --delete branch-name # Delete remote branch
If deletion fails, use force delete:
git branch -D develop
The -D flag is an alias for --delete --force, which removes the branch without checking merge status.
Cherry-Picking a Single Commit
git cherry-pick <commit-hash>
This applies the changes from a specific commit onto your current branch.
Reverting a Merge
To undo a merge operation, use git reset. The --soft option preserves changes in the staging area, while --hard discards all modificatinos.
To keep merged changes but undo the commit:
git reset --soft HEAD~1
To discard all changes since the merge:
git reset --hard HEAD~
HEAD~1 refers to the parent commit of the current HEAD, which is the state before the merge occurred.
Warning: The --hard option permanently discards all uncommitted changes. Verify with git status and git log before proceednig.
SSH Key Setup
Configure username and email globally:
git config --global user.name "developer"
git config --global user.email "developer@example.com"
Generate SSH key (press Enter through all prompts):
ssh-keygen -t rsa
Display the public key:
cat ~/.ssh/id_rsa.pub
Migrating a Repository
Step 1: Clone the old repository as a bare mirror
git clone --mirror <old-repo-url>
cd <repo-name>.git
Step 2: Update the push URL to the new repository
git remote set-url --push origin <new-repo-url>
Step 3: Push everything to the new repository
git push --mirror
Undoing a Commit
To revert a commit while keeping changes staged:
git reset --soft HEAD~1
HEAD~1moves back one commit--softleaves changes staged (similar to aftergit add)
If changes have already been pushed to a remote repository and you want to preserve history, use git revert instead, which creates a new commit that undoes the changes. The git reset --soft approach is preferred for local-only corrections.