Essential Git Commands Every Ops Engineer Needs for Reliable Deployments
This guide walks operations engineers through the core Git concepts, status checks, cloning strategies, branch handling, release directory design, conflict resolution, worktree usage, bisect debugging, and safe push practices, providing concrete command examples and scripts to make deployments reproducible and auditable.
Repository State Overview
Git tracks three areas: HEAD (the current commit), the index (staged changes), and the working tree (files on disk). Deployments should reference immutable commit IDs rather than moving branch names, recording the repository URL, full commit hash, artifact checksum, and deployment timestamp.
Inspecting the Repository
Useful one‑liner commands to verify the repository state before a release:
git rev-parse --show-toplevel
git status --short --branch
git rev-parse HEAD
git branch --show-current
git remote -vThe output of git status --short --branch shows staged ( A), modified ( M), deleted ( D) and untracked ( ??) files. Any non‑empty status should abort the release.
Cloning and Remote Configuration
Standard clone:
git clone <仓库地址> <本地目录>
cd <本地目录>
git remote -vShallow clone when history is not needed:
git clone --branch <分支名> --single-branch --depth 50 <仓库地址> <本地目录>If deeper history is later required, run git fetch --unshallow. Record the old remote URL before changing it for audit purposes.
Secure Authentication
Deploy machines should use read‑only deploy keys or short‑lived tokens. Private keys must have 0600 permissions and the host key should be stored in known_hosts. Avoid disabling host verification with StrictHostKeyChecking=no.
Commit‑Based Deployments
Deploy by checking out a specific commit in a detached HEAD state, ensuring the exact code version is used: git switch --detach <完整提交号> Never modify or commit on a deployment host; use --local config to keep identity changes local.
Release Directory Structure
Use an atomic symlink layout to avoid mixed‑state reads:
<应用根目录>/
├── current -> releases/<发布编号>
├── releases/
│ ├── <旧发布编号>/
│ └── <新发布编号>/
└── shared/ # configs, data, keys (outside Git)Prepare a new release in a fresh directory, run build and tests, then atomically switch current to the new release.
Pre‑Deployment Checks
Scripted checks should verify a clean working tree, matching commit IDs, and run language‑specific validators (e.g., nginx -t, systemd-analyze verify, bash -n). Example snippet:
if [[ -n "$(git status --porcelain=v1)" ]]; then
echo "Workspace dirty, aborting deployment" >&2
git status --short >&2
exit 1
fiHandling Conflicts and Recovery
If local changes block a switch, stash them with the ticket number:
git stash push --include-untracked -m "pre-deploy-<变更单号>"
# Resolve conflicts, then:
# git stash apply # or git stash pop after verification
# git stash drop # to discard the stashFor merge or rebase conflicts, abort safely:
# Merge conflict
git merge --abort
# Rebase conflict
git rebase --abortAvoid git reset --hard on shared branches; it discards uncommitted work without audit.
Selective Integration (Cherry‑Pick)
Apply a reviewed fix to a release branch while recording the original commit hash:
git switch <发布分支名>
git pull --ff-only origin <发布分支名>
git cherry-pick -x <修复提交号>
# Resolve conflicts if any
# git cherry-pick --continue
# or abort with git cherry-pick --abortBefore merging, review the diff and ensure any required migrations or configuration changes are also present.
Submodules and Git LFS
Initialize submodules after cloning:
git submodule update --init --recursive
# Verify each submodule
git submodule foreach --recursive 'git status --short --branch'Never run git pull inside a submodule on a deployment host; that would diverge from the commit recorded in the super‑project.
For repositories using Git LFS, fetch large files after cloning:
git lfs pull
git lfs ls-filesParallel Builds with Worktrees
Create isolated worktrees for multiple release candidates, sharing the object database but having independent HEAD, index, and working tree:
git worktree add --detach <工作树目录> <完整提交号>
# Verify the worktree
git -C <工作树目录> status --short --branchWhen finished, remove the worktree safely:
git worktree remove <工作树目录>
# Dry‑run prune first
git worktree prune --dry-runBisecting Regressions
Use git bisect to locate a bad commit between a known good and a known bad commit. Automated scripts must exit with 0 for good and non‑zero for bad.
git bisect start
git bisect bad <坏提交号>
git bisect good <好提交号>
# Run test script
if ./test.sh; then
git bisect good
else
git bisect bad
fi
# After finding the culprit
git bisect reset.gitignore and Index Flags
.gitignoreonly affects untracked files. To stop tracking a file that is already in the repository, use:
git rm --cached <文件路径>Index flags such as --skip-worktree or --assume-unchanged are not security mechanisms; they should be cleared before a release:
git update-index --no-skip-worktree <文件路径>
git update-index --no-assume-unchanged <文件路径>Safe Pushing
Deploy accounts should be read‑only. When a forced update is unavoidable, use git push --force-with-lease after verifying the remote state:
git fetch origin
git log --oneline origin/<分支名>..HEAD
# Verify remote diff
git push --force-with-lease origin <本地分支名>:<远端分支名>Protected branches on the server must enforce pull‑request reviews and status checks.
Repository Integrity Checks
Run a full integrity check before builds:
git fsck --full
# Monitor disk space and inode usage
df -h <仓库目录>
df -i <仓库目录>If corruption is detected, preserve the faulty directory for forensics, clone a fresh copy from the remote, and verify the target commit before proceeding.
Rollback Procedures
Rollback by switching the current symlink to a previously verified release directory and then reloading the service. Verify the rollback with health‑check endpoints and confirm the running commit matches the expected hash.
# Example rollback script
APP_ROOT="<应用根目录>"
ROLLBACK_RELEASE="/path/to/old/release"
ln -s -f "$ROLLBACK_RELEASE" "$APP_ROOT/.current.new"
mv -Tf "$APP_ROOT/.current.new" "$APP_ROOT/current"
# Verify
readlink -f "$APP_ROOT/current"Cleanup and Maintenance
Retain several verified releases before deleting old directories. List candidates by modification time:
find "${APP_ROOT}/releases" -mindepth 1 -maxdepth 1 -type d -printf '%T@ %p
' | sort -nAfter deletion, run git gc during low‑traffic windows to repack objects.
Auditable Release Records
Record the following for each deployment to create a verifiable audit trail:
git remote get-url origin
git rev-parse HEAD
git show -s --format='%H %aI %an %s' HEAD
git status --porcelain=v1
git diff --name-status <旧提交号> <新提交号>
# Combine with build artifact hash, dependency lockfile hash, and environment versionsThis information, together with artifact checksums and deployment timestamps, provides a complete, reproducible record of what was released.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
MaGe Linux Operations
Founded in 2009, MaGe Education is a top Chinese high‑end IT training brand. Its graduates earn 12K+ RMB salaries, and the school has trained tens of thousands of students. It offers high‑pay courses in Linux cloud operations, Python full‑stack, automation, data analysis, AI, and Go high‑concurrency architecture. Thanks to quality courses and a solid reputation, it has talent partnerships with numerous internet firms.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
