Git Version Control Commands
Category: DevOps and System Tools
Type: Linux Commands
Generated on: 2025-07-10 03:18:09
For: System Administration, Development & Technical Interviews
Git Version Control Cheatsheet (Linux - DevOps/SysAdmin)
Section titled “Git Version Control Cheatsheet (Linux - DevOps/SysAdmin)”This cheatsheet provides a comprehensive guide to Git commands, focusing on practical usage for DevOps and System Administration.
1. Command Overview
Section titled “1. Command Overview”Git is a distributed version control system used for tracking changes in source code during software development. It allows multiple developers to collaborate on projects, manage different versions of code, and revert to previous states if necessary. For SysAdmins, it can manage configuration files, scripts, and infrastructure-as-code.
2. Basic Syntax
Section titled “2. Basic Syntax”git <command> [options] [arguments]<command>: The Git command to execute (e.g.,clone,commit,push).[options]: Flags that modify the behavior of the command (e.g.,-m,-a,--force).[arguments]: Specific files, directories, or other inputs the command operates on.
3. Practical Examples
Section titled “3. Practical Examples”3.1. Initializing a Repository
Section titled “3.1. Initializing a Repository”# Create a new directory for your projectmkdir myprojectcd myproject
# Initialize a Git repository in the current directorygit init
# Example output:# Initialized empty Git repository in /home/user/myproject/.git/3.2. Cloning a Repository
Section titled “3.2. Cloning a Repository”# Clone a repository from a remote URL (e.g., GitHub)git clone https://github.com/user/repository.git
# Example output:# Cloning into 'repository'...# remote: Enumerating objects: 123, done.# remote: Counting objects: 100% (123/123), done.# remote: Compressing objects: 100% (80/80), done.# remote: Total 123 (delta 45), reused 90 (delta 20), pack reused 0# Receiving objects: 100% (123/123), 10.52 KiB | 3.51 MiB/s, done.# Resolving deltas: 100% (45/45), done.3.3. Adding and Committing Changes
Section titled “3.3. Adding and Committing Changes”# Check the status of your working directorygit status
# Example output (Untracked file):# On branch main## No commits yet## Untracked files:# (use "git add <file>..." to include in what will be committed)# new_file.txt## nothing added to commit but untracked files present (use "git add" to track)
# Add a file to the staging areagit add new_file.txt
# Example output (Staged file):# On branch main## No commits yet## Changes to be committed:# (use "git rm --cached <file>..." to unstage)# new file: new_file.txt
# Add all modified and untracked filesgit add .
# Commit the staged changes with a messagegit commit -m "Add new_file.txt and other changes"
# Example output:# [main (root-commit) 1234567] Add new_file.txt and other changes# 1 file changed, 1 insertion(+)# create mode 100644 new_file.txt3.4. Pushing Changes
Section titled “3.4. Pushing Changes”# Push your local commits to the remote repositorygit push origin main
# Example output:# Enumerating objects: 5, done.# Counting objects: 100% (5/5), done.# Delta compression using up to 8 threads# Compressing objects: 100% (3/3), done.# Writing objects: 100% (3/3), 275 bytes | 275.00 KiB/s, done.# Total 3 (delta 0), reused 0 (delta 0), pack reused 0# To https://github.com/user/repository.git# 1234567..89abcdef main -> main3.5. Pulling Changes
Section titled “3.5. Pulling Changes”# Pull the latest changes from the remote repositorygit pull origin main
# Example output (Up to date):# From https://github.com/user/repository# * branch main -> FETCH_HEAD# Already up to date.
# Example output (Pulling changes):# From https://github.com/user/repository# * branch main -> FETCH_HEAD# Updating 1234567..89abcdef# Fast-forward# new_file.txt | 1 +# 1 file changed, 1 insertion(+)3.6. Branching and Merging
Section titled “3.6. Branching and Merging”# Create a new branchgit branch feature-branch
# Switch to the new branchgit checkout feature-branch
# Example output:# Switched to branch 'feature-branch'
# Make changes on the feature branch...
# Commit your changesgit add .git commit -m "Implement feature X"
# Switch back to the main branchgit checkout main
# Merge the feature branch into the main branchgit merge feature-branch
# Example output (Fast-forward merge):# Updating 1234567..89abcdef# Fast-forward# new_file.txt | 1 +# 1 file changed, 1 insertion(+)
# Example output (Conflict during merge):# Auto-merging conflicting_file.txt# CONFLICT (content): Merge conflict in conflicting_file.txt# Automatic merge failed; fix conflicts and then commit the result.
# After resolving conflicts:git add conflicting_file.txtgit commit -m "Resolve merge conflicts"
# Delete the feature branch after merging (optional)git branch -d feature-branch
# Example output:# Deleted branch feature-branch (was 89abcdef).3.7. Viewing History
Section titled “3.7. Viewing History”# View the commit historygit log
# Example output:# commit 89abcdef0123456789abcdef0123456789abcdef (HEAD -> main, origin/main)# Author: User <user@example.com># Date: Thu Oct 26 10:00:00 2023 -0700## Implement feature X
# commit 123456789abcdef0123456789abcdef012345 (origin/HEAD)# Author: User <user@example.com># Date: Thu Oct 26 09:00:00 2023 -0700## Add new_file.txt and other changes
# View a specific commitgit show 89abcdef0123456789abcdef0123456789abcdef
# View the differences between two commitsgit diff 123456789abcdef0123456789abcdef012345 89abcdef0123456789abcdef0123456789abcdef
# View the differences between the working directory and the last commitgit diff3.8. Stashing Changes
Section titled “3.8. Stashing Changes”# Stash your current changes (useful for switching branches without committing)git stash
# Example Output:# Saved working directory and index state WIP on main: 1234567 Add some changes# HEAD is now at 1234567 Add some changes
# Apply the last stashed changesgit stash pop
# List all stashesgit stash list
# Example output:# stash@{0}: WIP on main: 1234567 Add some changes
# Apply a specific stash (e.g., the first stash)git stash apply stash@{0}
# Drop a specific stash (e.g., the first stash)git stash drop stash@{0}3.9. Reverting Changes
Section titled “3.9. Reverting Changes”# Revert a specific commit (creates a new commit that undoes the changes)git revert 123456789abcdef0123456789abcdef012345
# Example output:# [main 9876543] Revert "Add new_file.txt and other changes"# 1 file changed, 1 deletion(-)# delete mode 100644 new_file.txt
# Reset the staging area to match the last commitgit reset HEAD <file> # unstage a single file
# Undo the last commit (keep the changes in the working directory)git reset --soft HEAD^
# Undo the last commit and unstage the changes (keep the changes in the working directory)git reset HEAD^
# Discard all changes in the working directory (WARNING: This is destructive!)git reset --hard HEAD
# Go back to a specific commit (WARNING: This rewrites history. Use with caution, especially on shared branches.)git reset --hard <commit_hash>3.10. Ignoring Files
Section titled “3.10. Ignoring Files”# Create a .gitignore file to exclude files and directories from being trackedtouch .gitignore
# Edit the .gitignore file to add patterns:# Example .gitignore:# *.log# temp/# /config.ini# secrets.key
# Add the .gitignore file to the repositorygit add .gitignoregit commit -m "Add .gitignore file"4. Common Options
Section titled “4. Common Options”-m "message": Specifies a commit message.-a: Adds all modified and deleted files to the staging area automatically before committing. (equivalent togit add .beforegit commit)-u origin: Specifies the upstream tracking branch (used withgit push).-b <branch_name>: Creates a new branch (used withgit checkout).-d <branch_name>: Deletes a branch (used withgit branch).-f: Forces an operation (e.g.,git push -f). Use with caution! Can overwrite remote history.--amend: Modifies the last commit.--author="Name <email@example.com>": Specifies the author of a commit.--stat: Shows statistics about the changes in a commit (used withgit log).--graph: Displays a graphical representation of the commit history (used withgit log).--oneline: Displays the commit history in a concise, one-line format (used withgit log).-p: Shows the patch (diff) for each commit (used withgit logandgit show).
5. Advanced Usage
Section titled “5. Advanced Usage”5.1. Rebasing
Section titled “5.1. Rebasing”# Rebase your current branch onto another branch (e.g., main)git rebase main
# If conflicts occur during rebasing:# 1. Resolve the conflicts in the affected files.# 2. git add <conflicted_file># 3. git rebase --continue
# To abort a rebase:# git rebase --abort
# Rebase interactively (allows you to edit, reorder, or drop commits)git rebase -i HEAD~5 # Rebase the last 5 commits interactivelyWarning: Rebasing rewrites history. Avoid rebasing branches that are shared with others, as it can cause significant problems.
5.2. Cherry-Picking
Section titled “5.2. Cherry-Picking”# Cherry-pick a specific commit from another branchgit cherry-pick <commit_hash>5.3. Submodules
Section titled “5.3. Submodules”# Add a submodulegit submodule add <repository_url> <path>
# Initialize submodules after cloninggit submodule initgit submodule update
# Update submodulesgit submodule update --remote5.4. Git Hooks
Section titled “5.4. Git Hooks”Git hooks are scripts that Git executes before or after events such as: commit, push, receive, etc. They are stored in the .git/hooks directory.
# Example: pre-commit hook to check for syntax errors#!/bin/bash# pre-commit
# Check for syntax errors in Python filesfor file in $(git diff --cached --name-only --diff-filter=ACMR | grep '\.py$'); do echo "Checking syntax of $file..." python3 -m py_compile "$file" if [ $? -ne 0 ]; then echo "Syntax error found. Aborting commit." exit 1 fidone
exit 0Make the script executable:
chmod +x .git/hooks/pre-commit5.5. Git Attributes
Section titled “5.5. Git Attributes”Git attributes allow you to define per-file attributes for your repository. They are defined in the .gitattributes file.
# Example: .gitattributes file to handle line endings on different operating systems# Set the text attribute for all files* text=auto
# Ensure that .sh files are treated as text files and use LF line endings*.sh text eol=lf
# Ensure that .bat files are treated as text files and use CRLF line endings*.bat text eol=crlf5.6. Git Worktree
Section titled “5.6. Git Worktree”Worktrees allow you to have multiple working directories attached to a single repository. This is useful for working on multiple features or branches simultaneously without switching branches in the main working directory.
# Create a new worktreegit worktree add <path> <branch>
# List all worktreesgit worktree list
# Remove a worktreegit worktree remove <path>6. Tips & Tricks
Section titled “6. Tips & Tricks”-
Use descriptive commit messages: Clearly explain the changes you made in each commit.
-
Commit frequently: Break down large changes into smaller, logical commits.
-
Branch for new features: Isolate your work on separate branches to avoid disrupting the main codebase.
-
Review code before merging: Use pull requests to review code changes before merging them into the main branch.
-
Use
git bisectto find bugs: This command helps you quickly identify the commit that introduced a bug. -
Alias frequently used commands: Create aliases to shorten commonly used Git commands. For example:
Terminal window git config --global alias.st statusgit config --global alias.co checkoutgit config --global alias.br branchgit config --global alias.ci commitgit config --global alias.lg "log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit --date=relative"Now you can use
git st,git co,git br,git ci, andgit lg. -
Use
git blameto see who changed a specific line: Helpful for tracking down the history of a particular line of code. -
git clean -fdto remove untracked files and directories: Use with caution, as this is a destructive operation. Add-nfor a dry run. -
git update-index --assume-unchanged <file>: Tells Git to ignore changes to a file without removing it from the repository. Useful for local configuration files that shouldn’t be tracked. Usegit update-index --no-assume-unchanged <file>to revert. -
git config --global core.editor <editor>: Set your preferred text editor for Git operations like commit messages. For example:git config --global core.editor "nano"
7. Troubleshooting
Section titled “7. Troubleshooting”- “fatal: not a git repository (or any of the parent directories): .git”: You are not in a Git repository. Navigate to the root directory of your repository.
- Merge conflicts: Resolve the conflicts manually by editing the affected files, then
git addandgit commit. - “error: failed to push some refs to ‘<remote_url>’”: You may need to pull the latest changes from the remote repository before pushing. Alternatively, if you’re sure your changes are correct, you can use
git push --force origin main, but use this with extreme caution. - “error: pathspec '
' did not match any file(s) known to git” : The file you are trying to add or remove is not tracked by Git. Make sure the file exists and is not excluded by.gitignore. - Stuck in a rebase: Use
git rebase --abortto cancel the rebase. - Accidentally committed sensitive data: Use
git filter-branchorgit rebase -ito remove the sensitive data from the history. This is a complex process, so research it thoroughly before attempting. Consider using tools likegit-secretsto prevent accidental commits of sensitive data in the first place.
8. Related Commands
Section titled “8. Related Commands”ssh-keygen: Generates SSH keys for authentication with remote repositories.gitk: A graphical Git repository browser.tig: A text-mode Git repository browser.hub: A command-line tool that makes it easier to work with GitHub from the terminal.git-lfs: Git Large File Storage for managing large files in Git repositories.
This cheatsheet covers the most commonly used Git commands for DevOps and System Administration. Refer to the official Git documentation for a complete list of commands and options.