← Back to Articles         
Git Commands: Complete Beginner to Advanced Guide with Syntax and Examples

Git Commands: Complete Beginner to Advanced Guide with Syntax and Examples

Published on 20 Oct 2026     27 min read Git & GitHub
Git Commands from Beginner to Advanced
 

Git Commands – Complete Guide (Beginner to Advanced)

This guide covers Git commands from repository initialization to advanced history management, branching, merging, rebasing, remote operations, and troubleshooting.

Each command includes at least 5 explanation points, syntax, and practical examples.

Part 1 – Git Setup and Configuration

1. git --version – Check Git Version

Explanation:

  • Displays the installed Git version.

  • Confirms Git is installed and accessible from the terminal.

  • Useful when setting up Git on a new computer.

  • Helps identify compatibility with Git features.

  • Does not modify repositories or configuration.

Syntax:

git --version

Example:

git --version
# git version 2.47.1
 

2. git config – Configure Git Settings

Explanation:

  • Configures Git settings such as username and email address.

  • Git uses this identity when creating commits.

  • --global applies settings to repositories for the current user.

  • --local applies settings only to the current repository.

  • Repository-level settings generally override global settings.

Syntax:

git config --global user.name "Your Name"

git config --global user.email "you@example.com"

Example:

git config --global user.name "Syed"

git config --global user.email "syed@example.com"

Additional Syntax:

# Display all effective configuration values
git config --list

# Display configured username
git config user.name

# Display configured email
git config user.email

# Configure repository-specific username
git config --local user.name "Project Developer"

# Show configuration values and their sources
git config --list --show-origin
 

3. git init – Initialize a Git Repository

Explanation:

  • Creates a new Git repository in the current directory.

  • Creates a hidden .git directory for repository metadata.

  • Enables Git to track changes to project files.

  • Does not automatically stage or commit existing files.

  • Commonly used when starting a new software project.

Syntax:

git init

Example:

mkdir MyProject

cd MyProject

git init

Additional Syntax:

# Initialize with main as the initial branch
git init -b main

# Initialize a repository in a specific folder
git init MyProject
 

4. git clone – Clone a Remote Repository

Explanation:

  • Downloads an existing Git repository to your computer.

  • Retrieves repository files, commit history, and branch references.

  • Automatically creates a remote connection named origin.

  • Checks out the remote repository's default branch.

  • Commonly used when joining an existing development project.

Syntax:

git clone <repository-url>

Example:

git clone https://github.com/user/myproject.git

Additional Syntax:

# Clone into a specific folder
git clone https://github.com/user/myproject.git MyFolder

# Clone a specific branch
git clone -b develop https://github.com/user/myproject.git

# Shallow clone with recent history
git clone --depth 1 https://github.com/user/myproject.git
 

Part 2 – Git Status and File Tracking

5. git status – Check Repository Status

Explanation:

  • Displays the current working tree and staging status.

  • Identifies modified, deleted, and untracked files.

  • Shows which changes are staged for the next commit.

  • Displays the current branch and relevant tracking information.

  • Helps verify changes before committing or switching branches.

Syntax:

git status

Example:

git status

Additional Syntax:

# Short status output
git status -s

# Display branch information in short format
git status -sb
 

6. git add – Stage Files for Commit

Explanation:

  • Adds selected file changes to Git's staging area.

  • Prepares a snapshot of changes for the next commit.

  • Can stage individual files, folders, or all changes.

  • Staging does not create a commit or upload changes.

  • Changes made after staging must be staged again to include them.

Syntax:

git add <file-name>

Example:

git add Program.cs

Additional Syntax:

# Stage all changes in the repository
git add -A

# Stage changes under the current directory
git add .

# Stage multiple files
git add Program.cs appsettings.json

# Stage changes interactively
git add -p

# Stage all tracked file modifications and deletions
git add -u
 

7. git diff – View File Changes

Explanation:

  • Displays differences between file versions.

  • By default, compares working-tree changes against the staging area.

  • --staged shows changes prepared for the next commit.

  • Helps review code before staging or committing.

  • Does not modify files or repository history.

Syntax:

git diff

Example:

git diff Program.cs

Additional Syntax:

# Show staged changes
git diff --staged

# Compare two commits
git diff HEAD~1 HEAD

# Compare two branches
git diff main develop

# Show change summary
git diff --stat
 

8. git rm – Remove Tracked Files

Explanation:

  • Removes tracked files from the working directory and Git index.

  • Stages the deletion for the next commit.

  • --cached removes a file from tracking while keeping the local copy.

  • Useful when removing obsolete files or stopping tracking of generated files.

  • The deletion becomes part of repository history after committing.

Syntax:

git rm <file-name>

Example:

git rm oldfile.txt

Additional Syntax:

# Stop tracking but retain the local file
git rm --cached appsettings.Development.json

# Remove a tracked directory recursively
git rm -r OldFolder
 

9. git mv – Rename or Move Files

Explanation:

  • Moves or renames files already tracked by Git.

  • Stages the resulting file changes automatically.

  • Equivalent to moving a file and staging the relevant changes.

  • Git can recognize renames when comparing snapshots.

  • Useful when reorganizing project folders and source files.

Syntax:

git mv <old-path> <new-path>

Example:

git mv OldService.cs NewService.cs

Additional Syntax:

# Move a file into another directory
git mv Program.cs src/Program.cs
 

Part 3 – Git Commit and History

10. git commit – Commit Staged Changes

Explanation:

  • Saves staged changes as a new commit in local repository history.

  • Each commit has a unique identifier and associated metadata.

  • Commit messages describe the purpose of the changes.

  • Only staged content is included in a normal commit.

  • Committing locally does not automatically push changes to GitHub.

Syntax:

git commit -m "Commit message"

Example:

git add .

git commit -m "Added user authentication"

Additional Syntax:

# Stage and commit tracked file changes
git commit -am "Updated validation logic"

# Create an empty commit
git commit --allow-empty -m "Trigger pipeline"

# Open editor to write commit message
git commit
 

11. git log – View Commit History

Explanation:

  • Displays commits in repository history.

  • Shows commit IDs, authors, dates, and messages.

  • Helps identify when changes were introduced.

  • Supports filtering history by branch, author, date, or file.

  • Useful for debugging, auditing, and locating previous changes.

Syntax:

git log

Example:

git log --oneline

Additional Syntax:

# Show graphical commit history
git log --oneline --graph --all

# Display last five commits
git log -5

# Show commits by author
git log --author="Syed"

# Show history for a file
git log -- Program.cs

# Show commit changes
git log -p
 

12. git show – Display Commit Details

Explanation:

  • Displays information about a Git object, commonly a commit.

  • Shows commit metadata and the changes introduced by the commit.

  • Can inspect previous commits using their identifiers.

  • Useful when reviewing a bug fix or feature implementation.

  • Does not change the current branch or working files.

Syntax:

git show <commit-id>

Example:

git show a1b2c3d

Additional Syntax:

# Show latest commit
git show HEAD

# Show previous commit
git show HEAD~1

# Show only commit summary
git show --stat HEAD

# Show a file from a specific commit
git show HEAD:Program.cs
 

13. git commit --amend – Modify Last Commit

Explanation:

  • Replaces the most recent commit with an updated commit.

  • Can change its commit message or included file changes.

  • Generates a new commit ID because commit history is rewritten.

  • Useful when fixing mistakes immediately after committing.

  • Avoid amending shared commits unless the team has coordinated history changes.

Syntax:

git commit --amend

Example:

git add Program.cs

git commit --amend -m "Fixed login validation"

Additional Syntax:

# Change the last commit message
git commit --amend -m "Updated commit message"

# Add staged changes without changing the message
git commit --amend --no-edit
 

14. git blame – Identify Who Changed Code

Explanation:

  • Shows the last commit responsible for each line of a file.

  • Displays author and commit information alongside the code.

  • Helps investigate the history of particular lines.

  • Useful when understanding why existing code was written.

  • It identifies line history rather than determining responsibility for bugs.

Syntax:

git blame <file-name>

Example:

git blame Program.cs

Additional Syntax:

# Inspect selected lines
git blame -L 10,30 Program.cs

# Ignore whitespace-only changes
git blame -w Program.cs
 

Part 4 – Git Branch Management

15. git branch – List and Manage Branches

Explanation:

  • Displays local branches in the repository.

  • Marks the currently checked-out branch with an asterisk.

  • Can create, rename, and delete branches.

  • Branches allow independent feature development.

  • Creating a branch does not automatically switch to it.

Syntax:

git branch

Example:

git branch feature/login

Additional Syntax:

# List local branches
git branch

# List remote-tracking branches
git branch -r

# List local and remote-tracking branches
git branch -a

# Rename current branch
git branch -m main

# Delete a fully merged branch
git branch -d feature/login

# Force-delete a local branch
git branch -D feature/login
 

16. git switch – Switch Between Branches

Explanation:

  • Changes the currently active branch.

  • Updates working files to match the selected branch.

  • Provides a dedicated alternative to git checkout for branch switching.

  • Can create and switch to a new branch in one command.

  • May refuse switching when local changes would be overwritten.

Syntax:

git switch <branch-name>

Example:

git switch develop

Additional Syntax:

# Create and switch to a branch
git switch -c feature/payment

# Switch to previous branch
git switch -

# Create a branch from main
git switch -c feature/login main

# Track a remote branch
git switch --track origin/feature/login
 

17. git checkout – Switch Branches or Restore Files

Explanation:

  • Traditionally used to switch between Git branches.

  • Can create a branch and switch to it.

  • Also supports restoring files from commits or the index.

  • Modern Git separates these operations into git switch and git restore.

  • Still widely used in existing projects, scripts, and interview examples.

Syntax:

git checkout <branch-name>

Example:

git checkout develop

Additional Syntax:

# Create and switch to a new branch
git checkout -b feature/login

# Switch to main
git checkout main

# Restore file from HEAD (legacy syntax)
git checkout HEAD -- Program.cs
 

18. git merge – Merge Branch Changes

Explanation:

  • Integrates changes from another branch into the current branch.

  • May perform a fast-forward merge when histories permit.

  • Can create a merge commit when branches have diverged.

  • Preserves the original branch histories.

  • Conflicts must be resolved when Git cannot combine changes automatically.

Syntax:

git merge <source-branch>

Example:

git switch develop

git merge feature/login

Additional Syntax:

# Create a merge commit even if fast-forward is possible
git merge --no-ff feature/login

# Allow only fast-forward merges
git merge --ff-only feature/login

# Abort an in-progress conflicted merge
git merge --abort

Flow:

feature/login
     |
     v
  Development
     |
     v
git merge feature/login
     |
     v
   develop
 

19. git branch -d – Delete Local Branch

Explanation:

  • Deletes a local branch reference.

  • Commonly used after merging a completed feature.

  • The -d option checks whether the branch is appropriately merged.

  • The -D option forces deletion even if commits are unmerged.

  • Deleting a local branch does not delete its remote counterpart.

Syntax:

git branch -d <branch-name>

Example:

git switch develop

git branch -d feature/login

Additional Syntax:

# Force-delete local branch
git branch -D feature/login
 

Part 5 – Git Remote Repositories

20. git remote – Manage Remote Connections

Explanation:

  • Lists remote repositories configured for the local repository.

  • A remote is a named reference to another repository.

  • origin is the conventional default remote name.

  • Remote names can be customized according to project requirements.

  • Supports adding, renaming, removing, and inspecting remote connections.

Syntax:

git remote -v

Example:

git remote -v

Additional Syntax:

# Add a remote repository
git remote add origin https://github.com/user/project.git

# Change remote URL
git remote set-url origin https://github.com/user/newproject.git

# Rename a remote
git remote rename origin github

# Remove remote configuration
git remote remove origin

# Inspect remote information
git remote show origin
 

21. git push – Upload Local Commits

Explanation:

  • Sends local commits and references to a remote repository.

  • Typically used to publish completed work to GitHub or Azure Repos.

  • Requires suitable authentication and repository permissions.

  • Does not automatically merge changes into the remote's default branch.

  • A push may be rejected when the remote branch has diverged.

Syntax:

git push <remote-name> <branch-name>

Example:

git push origin develop

Additional Syntax:

# Push and configure upstream tracking
git push -u origin feature/login

# Push current branch using configured upstream
git push

# Push all local branches
git push origin --all

# Push tags
git push origin --tags

# Delete a remote branch
git push origin --delete feature/login
 

22. git fetch – Download Remote Changes

Explanation:

  • Downloads commits and references from a remote repository.

  • Updates remote-tracking branches such as origin/develop.

  • Does not automatically merge changes into the current branch.

  • Allows developers to inspect remote changes before integration.

  • Useful when synchronizing repository information safely.

Syntax:

git fetch <remote-name>

Example:

git fetch origin

Additional Syntax:

# Fetch all configured remotes
git fetch --all

# Remove stale remote-tracking references
git fetch --prune

# Fetch a specific branch
git fetch origin develop
 

23. git pull – Download and Integrate Changes

Explanation:

  • Fetches remote changes and integrates them into the current branch.

  • Usually performs a merge or rebase depending on configuration.

  • Commonly used to synchronize a local branch with its remote.

  • Can produce merge conflicts when local and remote changes overlap.

  • Developers should understand the configured pull strategy before using it.

Syntax:

git pull <remote-name> <branch-name>

Example:

git switch develop

git pull origin develop

Additional Syntax:

# Pull using rebase
git pull --rebase origin develop

# Allow only fast-forward updates
git pull --ff-only origin develop

# Pull using an explicit merge strategy
git pull --no-rebase origin develop
 

24. git push -u – Configure Upstream Branch

Explanation:

  • Pushes a branch and establishes its upstream tracking relationship.

  • Connects a local branch to a remote branch.

  • Simplifies future git push and git pull commands.

  • Commonly used when publishing a newly created feature branch.

  • Upstream tracking helps Git report ahead and behind commit counts.

Syntax:

git push -u <remote-name> <branch-name>

Example:

git switch -c feature/login

git push -u origin feature/login

Subsequent Commands:

git push

git pull
 

Part 6 – Undoing Changes and Recovery

25. git restore – Restore Working Files

Explanation:

  • Restores file contents from a selected source.

  • By default, restores the working file from the staging area.

  • Can also unstage changes using the --staged option.

  • Useful for discarding unwanted local modifications.

  • Restoring working-tree changes can permanently discard uncommitted work.

Syntax:

git restore <file-name>

Example:

git restore Program.cs

Additional Syntax:

# Restore all tracked working-tree files
git restore .

# Unstage a file
git restore --staged Program.cs

# Restore a file from HEAD
git restore --source=HEAD Program.cs

# Restore both index and working tree from HEAD
git restore --source=HEAD --staged --worktree Program.cs
 

26. git reset – Reset Commits or Staging

Explanation:

  • Moves the current branch reference to a specified commit.

  • Can also reset the staging area without moving branch history.

  • --soft preserves staged changes when moving the branch.

  • --mixed resets the index while preserving working-tree changes.

  • --hard resets tracked files and can permanently discard local changes.

Syntax:

git reset <commit-id>

Example:

git reset --soft HEAD~1

Additional Syntax:

# Undo last commit and retain staged changes
git reset --soft HEAD~1

# Undo last commit and unstage changes
git reset --mixed HEAD~1

# Discard last commit and tracked file changes
git reset --hard HEAD~1

# Unstage a file
git reset HEAD Program.cs

Comparison:

Option

Moves HEAD

Keeps changes staged

Keeps working changes

--soft

Yes

Yes

Yes

--mixed

Yes

No

Yes

--hard

Yes

No

No

 

27. git revert – Reverse an Existing Commit

Explanation:

  • Creates a new commit that reverses changes from an earlier commit.

  • Preserves existing commit history rather than rewriting it.

  • Commonly used to undo changes already pushed to shared branches.

  • Can produce conflicts if subsequent commits modified the same code.

  • Generally safer than resetting published branch history.

Syntax:

git revert <commit-id>

Example:

git revert a1b2c3d

Additional Syntax:

# Revert latest commit
git revert HEAD

# Prepare a revert without committing
git revert --no-commit a1b2c3d

# Abort an in-progress revert
git revert --abort
 

28. git clean – Remove Untracked Files

Explanation:

  • Removes untracked files from the working directory.

  • Useful for cleaning generated files and temporary build outputs.

  • Does not remove tracked files.

  • The -n option previews files that would be removed.

  • Removed untracked files may not be recoverable through Git.

Syntax:

git clean -n

Example:

# Preview untracked files
git clean -n

# Remove untracked files
git clean -f

Additional Syntax:

# Preview untracked directories
git clean -nd

# Remove untracked files and directories
git clean -fd

# Include ignored files (dangerous)
git clean -fdx
 

Part 7 – Git Stash

29. git stash – Temporarily Save Changes

Explanation:

  • Temporarily stores uncommitted changes outside the working tree.

  • Useful when switching tasks before changes are ready to commit.

  • By default, stashes tracked working-tree and staged changes.

  • Untracked files require the -u option to be included.

  • Saved changes can be restored later using stash commands.

Syntax:

git stash

Example:

git stash push -m "Login feature work"

Additional Syntax:

# Stash tracked changes
git stash

# Include untracked files
git stash -u

# Stash with description
git stash push -m "Payment module changes"

# Stash selected file
git stash push -- Program.cs
 

30. git stash list – View Saved Stashes

Explanation:

  • Displays saved stash entries.

  • Each entry has an identifier such as stash@{0}.

  • Shows the branch context and stash description.

  • Helps identify which saved changes to restore.

  • Does not modify the working directory or stash contents.

Syntax:

git stash list

Example:

git stash list

Sample Output:

stash@{0}: On develop: Payment module changes
stash@{1}: On develop: Login feature work
 

31. git stash apply – Restore Stashed Changes

Explanation:

  • Applies changes saved in a stash entry.

  • Keeps the stash entry available for future use.

  • Can apply a selected stash instead of the latest one.

  • May produce conflicts if current files have changed.

  • Useful when reusing saved changes across branches.

Syntax:

git stash apply

Example:

git stash apply stash@{0}

Additional Syntax:

# Apply latest stash
git stash apply

# Apply specific stash
git stash apply stash@{1}

# Attempt to restore staged state too
git stash apply --index
 

32. git stash pop – Restore and Remove Stash

Explanation:

  • Applies changes from a stash entry.

  • Removes the stash entry after a successful application.

  • Commonly used when resuming temporarily interrupted work.

  • If application conflicts occur, the stash is normally retained.

  • Differs from apply, which keeps the stash entry.

Syntax:

git stash pop

Example:

git stash pop

Additional Syntax:

# Pop a specific stash
git stash pop stash@{1}

# Delete a specific stash without applying
git stash drop stash@{0}

# Delete all stash entries
git stash clear
 

Part 8 – Advanced Branch Integration

33. git rebase – Reapply Commits onto Another Branch

Explanation:

  • Replays commits from one branch onto another base.

  • Produces a more linear history than a typical merge.

  • Rewritten commits receive new commit identifiers.

  • Often used to update feature branches before creating pull requests.

  • Avoid rebasing shared commits without coordinating with collaborators.

Syntax:

git rebase <base-branch>

Example:

git switch feature/login

git fetch origin

git rebase origin/develop

Additional Syntax:

# Continue after resolving conflicts
git rebase --continue

# Abort rebase
git rebase --abort

# Skip the current commit
git rebase --skip

Flow:

Before Rebase:

develop:       A---B---C
                    \
feature/login:       D---E


After Rebase:

develop:       A---B---C
                        \
feature/login:           D'---E'
 

34. git rebase -i – Interactive Rebase

Explanation:

  • Allows editing a sequence of commits interactively.

  • Can reorder, combine, remove, or edit commits.

  • Commonly used to clean up local feature-branch history.

  • Changes commit IDs for rewritten commits and their descendants.

  • Should be used carefully when commits have already been shared.

Syntax:

git rebase -i HEAD~3

Example:

git rebase -i HEAD~3

Interactive Options:

pick    - Keep commit
reword  - Change commit message
edit    - Pause to modify commit
squash  - Combine with previous commit
fixup   - Combine and discard this message
drop    - Remove commit
 

35. git cherry-pick – Apply a Specific Commit

Explanation:

  • Copies the changes introduced by selected commits onto the current branch.

  • Useful when only one fix is needed from another branch.

  • Creates a new commit with a different identifier in normal use.

  • Does not merge the complete source branch history.

  • Can produce conflicts when changes overlap with existing code.

Syntax:

git cherry-pick <commit-id>

Example:

git switch main

git cherry-pick a1b2c3d

Additional Syntax:

# Cherry-pick multiple commits
git cherry-pick a1b2c3d e4f5a6b

# Apply changes without committing
git cherry-pick -n a1b2c3d

# Continue after resolving conflicts
git cherry-pick --continue

# Abort cherry-pick
git cherry-pick --abort
 

36. git merge --squash – Combine Branch Changes

Explanation:

  • Combines changes from another branch into the current index and working tree.

  • Allows creating one commit containing the combined changes.

  • Does not create a normal merge commit or record a merge parent.

  • Useful for keeping feature history compact on the target branch.

  • The final commit must be created manually.

Syntax:

git merge --squash <branch-name>

Example:

git switch develop

git merge --squash feature/login

git commit -m "Implemented login feature"
 

Part 9 – Git Tags and Releases

37. git tag – Create Version Tags

Explanation:

  • Assigns a readable name to a specific commit.

  • Commonly used for software releases such as v1.0.0.

  • Supports lightweight and annotated tags.

  • Annotated tags store additional metadata and messages.

  • Tags are not automatically pushed with ordinary branch pushes.

Syntax:

git tag <tag-name>

Example:

git tag v1.0.0

Additional Syntax:

# Create annotated tag
git tag -a v1.0.0 -m "Version 1.0 release"

# List tags
git tag

# Show tag information
git show v1.0.0

# Push one tag
git push origin v1.0.0

# Push all tags
git push origin --tags
 

38. git tag -d – Delete Git Tags

Explanation:

  • Deletes a tag reference from the local repository.

  • Useful when a tag was created incorrectly.

  • Does not delete the commit referenced by the tag.

  • Deleting a local tag does not remove its remote copy.

  • Published release tags should generally be treated as immutable.

Syntax:

git tag -d <tag-name>

Example:

git tag -d v1.0.0

Additional Syntax:

# Delete tag from remote
git push origin --delete v1.0.0
 

Part 10 – Advanced Git Troubleshooting

39. git reflog – Recover Previous HEAD Positions

Explanation:

  • Records local movements of HEAD and other references.

  • Helps locate commits after resets, rebases, or branch changes.

  • Can recover commits that are no longer reachable from a branch.

  • Reflog records are local and expire according to Git configuration.

  • Useful for recovering from accidental history modifications.

Syntax:

git reflog

Example:

git reflog

Recovery Example:

# Locate previous commit
git reflog

# Create a recovery branch at that commit
git branch recovery a1b2c3d

# Switch to recovered branch
git switch recovery
 

40. git bisect – Find the Commit That Introduced a Bug

Explanation:

  • Uses binary search to identify a problematic commit.

  • Requires a known good commit and a known bad commit.

  • Checks intermediate commits to narrow the search.

  • Efficient for investigating regressions in large commit histories.

  • Can be automated with a test script that returns success or failure.

Syntax:

git bisect start

Example:

git bisect start

git bisect bad

git bisect good a1b2c3d

Additional Syntax:

# Mark current revision as good
git bisect good

# Mark current revision as bad
git bisect bad

# Finish and restore original checkout
git bisect reset
 

41. git grep – Search Repository Content

Explanation:

  • Searches text within Git-tracked repository content.

  • Useful for finding method names, configuration keys, or TODO comments.

  • Can search the current working tree or a specified revision.

  • Supports line numbers and regular-expression matching.

  • Often faster and more focused than searching the entire project directory.

Syntax:

git grep <search-text>

Example:

git grep "ConnectionString"

Additional Syntax:

# Show matching line numbers
git grep -n "TODO"

# Case-insensitive search
git grep -i "authentication"

# Search content at a specific revision
git grep "Login" HEAD
 

42. git log -S – Find When Text Was Added or Removed

Explanation:

  • Searches commit history for changes in the occurrence count of a string.

  • Useful when investigating when a method or setting appeared or disappeared.

  • Searches historical changes rather than only current file content.

  • Can be restricted to a specific file.

  • -G is an alternative for matching added or removed lines using a regular expression.

Syntax:

git log -S"search-text"

Example:

git log -S"ValidateToken" --oneline

Additional Syntax:

# Search historical changes in one file
git log -S"ConnectionString" -- appsettings.json

# Search changed lines using regex
git log -G"Validate.*Token" --oneline
 

43. git worktree – Work on Multiple Branches Simultaneously

Explanation:

  • Creates additional working directories linked to the same repository.

  • Allows working on different branches without repeatedly switching branches.

  • Useful when handling urgent production fixes during feature development.

  • Shares Git object storage while maintaining separate working files.

  • A branch generally cannot be checked out in multiple worktrees simultaneously.

Syntax:

git worktree add <folder> <branch>

Example:

git worktree add ../production-fix main

Additional Syntax:

# Create a new branch in a separate worktree
git worktree add -b hotfix/login ../hotfix main

# List worktrees
git worktree list

# Remove a worktree
git worktree remove ../production-fix

# Clean stale worktree metadata
git worktree prune
 

44. git push --force-with-lease – Safely Force-Update a Branch

Explanation:

  • Updates a remote branch even when a normal fast-forward push is impossible.

  • Commonly needed after rebasing previously pushed commits.

  • Adds a safety check against overwriting unexpected remote updates.

  • Safer than plain --force, but can still rewrite shared history.

  • Should normally be restricted to branches where history rewriting is permitted.

Syntax:

git push --force-with-lease <remote-name> <branch-name>

Example:

git push --force-with-lease origin feature/login
 

45. git fsck – Check Repository Integrity

Explanation:

  • Examines Git objects and their connectivity.

  • Helps detect missing or corrupted repository objects.

  • Can report dangling objects that are no longer referenced.

  • Useful during advanced troubleshooting and repository recovery.

  • Does not automatically repair every reported problem.

Syntax:

git fsck

Example:

git fsck --full

Additional Syntax:

# Check repository and show unreachable objects
git fsck --full --unreachable

# Display dangling objects
git fsck --no-reflogs --unreachable
 

Part 11 – Repository Maintenance and Advanced Features

46. git gc – Optimize Repository Storage

Explanation:

  • Performs Git repository housekeeping and garbage collection.

  • Can consolidate loose objects into pack files.

  • Helps optimize repository storage and performance.

  • Git often performs maintenance automatically when necessary.

  • Aggressive cleanup options should be used carefully.

Syntax:

git gc

Example:

git gc

Additional Syntax:

# Perform more aggressive optimization
git gc --aggressive
 

47. git submodule – Manage Nested Repositories

Explanation:

  • Allows one Git repository to reference another repository.

  • Commonly used for shared libraries or separately versioned components.

  • The parent repository records a specific submodule commit.

  • Submodule contents require initialization and updating after cloning.

  • Adds dependency-management complexity and requires careful version control.

Syntax:

git submodule add <repository-url> <path>

Example:

git submodule add https://github.com/user/shared-library.git libs/shared-library

Additional Syntax:

# Initialize and update submodules
git submodule update --init --recursive

# Clone including submodules
git clone --recurse-submodules https://github.com/user/project.git

# Display submodule status
git submodule status
 

48. git archive – Export Repository Files

Explanation:

  • Creates an archive containing files from a Git tree.

  • Useful for distributing source code without Git metadata.

  • Supports formats such as ZIP and TAR.

  • Can export a branch, tag, or commit snapshot.

  • Does not include uncommitted working-directory changes.

Syntax:

git archive --format=zip --output=<file.zip> <branch>

Example:

git archive --format=zip --output=release.zip main

Additional Syntax:

# Export a release tag
git archive --format=tar --output=release.tar v1.0.0
 

49. git bundle – Transfer Repository History Offline

Explanation:

  • Packages Git objects and references into a single bundle file.

  • Useful when transferring repositories without network access.

  • Can include selected branches and tags.

  • Bundle files can be cloned or fetched from.

  • Unlike a source ZIP, bundles preserve Git history.

Syntax:

git bundle create <file.bundle> --all

Example:

git bundle create project-backup.bundle --all

Additional Syntax:

# Verify bundle
git bundle verify project-backup.bundle

# Clone from bundle
git clone project-backup.bundle RestoredProject
 

50. git sparse-checkout – Check Out Selected Directories

Explanation:

  • Allows the working tree to contain only selected repository paths.

  • Useful when working with large monorepositories.

  • Reduces the number of files present in the working directory.

  • Does not necessarily reduce downloaded Git history by itself.

  • Often combined with partial cloning for more efficient large-repository workflows.

Syntax:

git sparse-checkout set <directory>

Example:

git sparse-checkout init --cone

git sparse-checkout set src/API

Additional Syntax:

# Add another directory
git sparse-checkout add src/Application

# Restore full working-tree checkout
git sparse-checkout disable

# View sparse-checkout configuration
git sparse-checkout list
 

Part 12 – Real-World Git Workflows

51. Create a Feature Branch and Push to Remote

Explanation:

  • Starts development from an updated shared branch.

  • Creates an isolated feature branch for new changes.

  • Stages and commits the implementation locally.

  • Pushes the feature branch to the remote repository.

  • Enables creating a pull request for review and integration.

Syntax and Example:

git switch develop

git pull --ff-only origin develop

git switch -c feature/login

git add .

git commit -m "Implemented login feature"

git push -u origin feature/login
 

52. Merge a Completed Feature into Develop

Explanation:

  • Integrates completed feature changes into the development branch.

  • Developers commonly use pull requests for review and approval.

  • Local merging is useful when direct integration is permitted.

  • Conflicts may require manual resolution.

  • The feature branch can be deleted after successful integration.

Syntax and Example:

git switch develop

git pull --ff-only origin develop

git merge feature/login

git push origin develop

git branch -d feature/login
 

53. Update a Feature Branch Using Rebase

Explanation:

  • Synchronizes a feature branch with the latest development changes.

  • Replays feature commits on top of the updated base.

  • Helps maintain a linear commit history.

  • Conflicts must be resolved before the rebase can continue.

  • Previously pushed feature branches may require a coordinated force-with-lease push.

Syntax and Example:

git fetch origin

git switch feature/login

git rebase origin/develop

If Conflicts Occur:

# Edit files to resolve conflicts

git add Program.cs

git rebase --continue
 

54. Apply a Production Hotfix Using Cherry-Pick

Explanation:

  • Allows a selected bug-fix commit to be applied to another branch.

  • Useful when production requires a fix without unrelated development changes.

  • Avoids merging an entire feature or development branch.

  • The copied fix becomes a new commit on the destination branch.

  • Teams should ensure the fix is also present in other relevant release branches.

Syntax and Example:

git switch main

git pull --ff-only origin main

git cherry-pick a1b2c3d

git push origin main
 

55. Recover from an Accidental Hard Reset

Explanation:

  • Uses local reflog information to locate a previous commit.

  • Can recover committed work lost from the current branch reference.

  • Works only while the relevant objects and reflog entries remain available.

  • Creating a recovery branch is safer than immediately resetting again.

  • Uncommitted changes discarded by a hard reset are not normally recoverable through reflog.

Syntax and Example:

# Inspect recent HEAD movements
git reflog

# Create recovery branch at the lost commit
git branch recovery a1b2c3d

# Inspect recovered history
git switch recovery

git log --oneline
 

Git Command Quick Reference

Category

Important commands

Setup

git init, git clone, git config

File tracking

git status, git add, git diff, git rm, git mv

Commits

git commit, git log, git show, git blame

Branching

git branch, git switch, git checkout

Integration

git merge, git rebase, git cherry-pick

Remote

git remote, git fetch, git pull, git push

Undo

git restore, git reset, git revert, git clean

Temporary work

git stash, git stash apply, git stash pop

Releases

git tag, git archive, git bundle

Troubleshooting

git reflog, git bisect, git grep, git fsck

Advanced

git worktree, git submodule, git gc, git sparse-checkout

Important: Git itself does not create or approve pull requests through a built-in git command. Pull requests are typically managed through GitHub, Azure DevOps, GitLab, or their respective CLI tools.

This reference covers 55 commands and practical workflows, progressing from initial Git configuration to advanced repository management.

← Back to Articles