Git Version Control Mastery
· Pavan Y N · git, devops, cicd
Git is the version control system behind most modern software delivery, and it is the foundation of DevOps practices such as CI/CD (continuous integration and continuous delivery) and GitOps. EduGeek explains the commands and workflows that matter in day-to-day team work: branching, conflict resolution, history cleanup, commit signing, large-repository features, hooks, and a CI pipeline. The commands were checked against Git 2.53; the current release, Git 2.56, was published on September 28, 2026.
# Why Git matters in DevOps
Git gives teams:
- →Collaboration: many developers work in parallel on separate branches.
- →Version history: a complete, attributable record of every change.
- →Branching: cheap, isolated lines of development.
- →Recovery: any committed state can be restored, and
git reflogcan find commits that no branch points to anymore. - →Integration: every CI/CD system and GitOps agent starts from a Git repository.
# Essential Git commands
## Repository setup
# Name the default branch once, so new repositories start on "main"
git config --global init.defaultBranch main
# Initialize a repository
git init
# Clone an existing repository
git clone https://github.com/user/repo.git
# Check repository status
git status
Without init.defaultBranch, git init still creates a branch named master, even on current Git versions.
## Basic workflow
# Stage changes (review them hunk by hunk with -p)
git add specific-file.txt
git add -p
# Commit changes
git commit -m "Descriptive commit message"
# Push a new branch and set its upstream
git push -u origin main
# Fetch and integrate the latest remote changes
git pull --rebase
git add . stages everything in the working tree, including files that were never meant to be committed, so prefer naming files or using git add -p.
Plain git pull fails when local and remote history have diverged: Git stops with "Need to specify how to reconcile divergent branches". Choose a policy once instead of answering the prompt each time:
# Rebase local commits on top of the fetched ones
git config --global pull.rebase true
# Or refuse anything that is not a fast-forward
git config --global pull.ff only
## Switching branches and restoring files
git checkout does several unrelated jobs. Two newer commands split them apart.
# Create a branch and switch to it
git switch -c feature/login
# Go back to the previous branch
git switch -
# Discard unstaged changes in a file
git restore path/to/file
# Unstage a file but keep the changes
git restore --staged path/to/file
# Restore a file as it exists on another branch
git restore --source=main path/to/file
# Branching strategies
## GitFlow
GitFlow uses long-lived branches: main (production), develop (integration), and feature/*, release/*, and hotfix/* branches. It suits software that ships explicit versions or must support several versions in the field. The author of the original GitFlow article added a note in 2020 saying it is a poor fit for continuously delivered web applications and recommending a much simpler workflow, such as GitHub flow, for those teams.
## Trunk-based development
Trunk-based development works on a single main branch with short-lived branches, frequent integration, and feature flags for unfinished work. The DevOps Research and Assessment (DORA) research on continuous delivery describes it as branches and forks with very short lifetimes (less than a day, for example) before merging into the mainline, with fewer than three active branches. It is the natural fit for continuous deployment.
Both models are compatible with protecting main: GitHub rulesets (and branch protection rules) can restrict who may push, require pull request reviews, and block force pushes.
# Handling merge conflicts
A conflict occurs when two branches change the same lines. Git marks the file:
<<<<<<< HEAD
Your changes
=======
Their changes
>>>>>>> branch-name
A resolution workflow looks like this:
# List the files that still conflict
git diff --name-only --diff-filter=U
# After editing the files and removing the markers
git add path/to/file
git commit # for a merge
# git rebase --continue # when the conflict came from a rebase
# Give up and return to the state before the merge
git merge --abort
Setting merge.conflictStyle to zdiff3 adds the common ancestor to the markers, which makes it clear what each side actually changed:
git config --global merge.conflictStyle zdiff3
<<<<<<< HEAD
Your changes
||||||| 4e2f749
Original text
=======
Their changes
>>>>>>> branch-name
# Pull request best practices
- •Keep pull requests (PRs) small: one feature or fix per pull request.
- •Write clear descriptions: explain what changed and why.
- •Add context: link to issues and attach screenshots when the change is visible.
- •Request specific reviewers: choose people with relevant expertise.
- •Respond promptly: unanswered review comments are where pull requests stall.
- •Use draft PRs: share work in progress without asking for a merge.
# Advanced Git techniques
## Interactive rebase
# Clean up the last three commits
git rebase -i HEAD~3
In the todo list, pick keeps a commit, reword changes its message, edit stops so the commit can be amended, squash and fixup fold a commit into the previous one (fixup discards its message), and drop removes it. Commits can be marked for folding as they are made:
# Record a fix for an earlier commit...
git commit --fixup <commit-hash>
# ...and let the rebase move and fold it automatically
git rebase -i --autosquash <commit-hash>~1
When several branches are stacked on one another, git rebase --update-refs moves every branch that points at a rebased commit, and rebase.updateRefs=true makes that the default.
## Cherry-pick
# Apply a specific commit to the current branch
git cherry-pick <commit-hash>
## Stash
# Save work temporarily, including untracked files
git stash push -u -m "Work in progress"
# List stashes
git stash list
# Re-apply the newest stash and keep it, or apply it and drop it
git stash apply stash@{0}
git stash pop
git stash save is deprecated in favor of git stash push, which also accepts pathspecs.
## Rewriting history safely
After a rebase, the remote branch has to be overwritten. Use --force-with-lease, which refuses to push if the remote branch has moved since your last fetch:
git push --force-with-lease origin feature/login
Plain --force would silently discard a teammate's commits. Never rewrite history on shared branches such as main. If something goes wrong locally, git reflog lists where HEAD has been, and git revert <commit-hash> creates a new commit that undoes an earlier one without rewriting anything.
# Signing commits with an SSH key
Git can sign commits with the SSH key many developers already use, instead of requiring a GNU Privacy Guard (GPG) setup.
git config --global gpg.format ssh
git config --global user.signingkey ~/.ssh/id_ed25519.pub
git config --global commit.gpgsign true
# To verify signatures locally, list trusted keys in an allowed-signers file
git config --global gpg.ssh.allowedSignersFile ~/.config/git/allowed_signers
git log --show-signature -1
Each line of the allowed-signers file pairs an email address with a public key, for example dev@example.com ssh-ed25519 AAAA.... A valid signature prints Good "git" signature for dev@example.com.
# Working with large repositories
Three features keep very large repositories usable:
# Partial clone: download file contents on demand, with a sparse working tree
git clone --filter=blob:none --sparse https://github.com/org/monorepo.git
cd monorepo
git sparse-checkout set services/payments docs
# Background maintenance: prefetch and commit-graph updates on a schedule
git maintenance start
--filter=blob:none omits file contents until they are needed. git sparse-checkout set limits the working tree to the listed directories; in the default cone mode it also includes files in the top-level directory and files directly under each parent directory. git maintenance start registers the repository and installs a scheduler (systemd timers, launchctl, schtasks, or cron) that runs maintenance tasks hourly. It changes your global Git configuration and system scheduler, so run it deliberately.
# Git hooks for automation
Hooks are scripts that Git runs at defined points. A pre-commit hook can block a commit that fails fast checks:
#!/bin/sh
# .githooks/pre-commit: run fast checks before every commit
npm run lint --silent || {
echo "Lint failed. Commit aborted."
exit 1
}
Hooks in .git/hooks are not part of a clone, so teams that want shared hooks commit them to the repository and point Git at the directory:
chmod +x .githooks/pre-commit
git config core.hooksPath .githooks
Keep pre-commit hooks fast, because a slow hook trains people to bypass it with git commit --no-verify. Run the full test suite in CI, where it cannot be skipped.
# Best practices
- •Commit often: small, focused commits are easier to review and revert.
- •Write good messages: say why the change was made, not only what changed.
- •Integrate regularly: use
git pull --rebaseor mergemaininto long-running branches. - •Protect
main: enforce pull requests with rulesets or branch protection rather than relying on habit. - •Review before merge: code review is the main quality gate.
- •Tag releases:
git tag -a v1.4.0 -m "Release 1.4.0"marks the exact commit that shipped.
# Common mistakes to avoid
- →Committing secrets. Deleting a file in a later commit does not remove it from history. Rotate the credential first, then remove it from history with
git filter-repo; the Git documentation recommends it overgit filter-branch, which it describes as having many pitfalls. - →Committing large binary files. Use Git Large File Storage (LFS) or an artifact repository instead.
- →Writing unclear commit messages.
- →Working directly on
main. - →Starting new work without pulling first.
- →Force pushing to shared branches, or using
--forceinstead of--force-with-lease.
# Git in CI/CD pipelines
# GitHub Actions
name: CI
on:
push:
branches: [main]
pull_request:
branches: [main]
jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v7
- uses: actions/setup-node@v7
with:
node-version: 24
cache: npm
- name: Install dependencies
run: npm ci
- name: Run tests
run: npm test
The workflow installs Node.js explicitly and uses npm ci for a reproducible install from the lockfile. The same repository then feeds deployment: the Jenkins CI/CD guide shows a CI server consuming it, and the GitOps guide shows a cluster agent that deploys whatever the configuration repository says. For where Git fits in the whole delivery loop, see the DevOps lifecycle guide.
# Key takeaways
- →Set
init.defaultBranchandpull.rebase(orpull.ff only) once, because Git still defaults tomasterand a plaingit pullfails on diverged history. - →Use
git switchandgit restoreinstead of overloadinggit checkout, andgit stash pushinstead of the deprecatedgit stash save. - →Choose a branching model that matches how you ship: GitFlow for explicitly versioned releases, trunk-based development for continuous delivery.
- →Rewrite history only on your own branches, and push it with
--force-with-leaseso you cannot overwrite a teammate's work. - →Sign commits with an SSH key by setting
gpg.format ssh, and verify them with an allowed-signers file. - →Use partial clone and sparse checkout for monorepos, and keep shared hooks in the repository through
core.hooksPath. - →Treat a leaked secret as compromised: rotate it, then remove it from history with
git filter-repo.
# Further reading
Test yourself: Git Version Control Mastery assessment