Skip to content

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.

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.

Terminal window
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.
Terminal window
# Create a new directory for your project
mkdir myproject
cd myproject
# Initialize a Git repository in the current directory
git init
# Example output:
# Initialized empty Git repository in /home/user/myproject/.git/
Terminal window
# 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.
Terminal window
# Check the status of your working directory
git 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 area
git 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 files
git add .
# Commit the staged changes with a message
git 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.txt
Terminal window
# Push your local commits to the remote repository
git 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 -> main
Terminal window
# Pull the latest changes from the remote repository
git 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(+)
Terminal window
# Create a new branch
git branch feature-branch
# Switch to the new branch
git checkout feature-branch
# Example output:
# Switched to branch 'feature-branch'
# Make changes on the feature branch...
# Commit your changes
git add .
git commit -m "Implement feature X"
# Switch back to the main branch
git checkout main
# Merge the feature branch into the main branch
git 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.txt
git 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).
Terminal window
# View the commit history
git 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 commit
git show 89abcdef0123456789abcdef0123456789abcdef
# View the differences between two commits
git diff 123456789abcdef0123456789abcdef012345 89abcdef0123456789abcdef0123456789abcdef
# View the differences between the working directory and the last commit
git diff
Terminal window
# 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 changes
git stash pop
# List all stashes
git 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}
Terminal window
# 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 commit
git 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>
Terminal window
# Create a .gitignore file to exclude files and directories from being tracked
touch .gitignore
# Edit the .gitignore file to add patterns:
# Example .gitignore:
# *.log
# temp/
# /config.ini
# secrets.key
# Add the .gitignore file to the repository
git add .gitignore
git commit -m "Add .gitignore file"
  • -m "message": Specifies a commit message.
  • -a: Adds all modified and deleted files to the staging area automatically before committing. (equivalent to git add . before git commit)
  • -u origin: Specifies the upstream tracking branch (used with git push).
  • -b <branch_name>: Creates a new branch (used with git checkout).
  • -d <branch_name>: Deletes a branch (used with git 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 with git log).
  • --graph: Displays a graphical representation of the commit history (used with git log).
  • --oneline: Displays the commit history in a concise, one-line format (used with git log).
  • -p: Shows the patch (diff) for each commit (used with git log and git show).
Terminal window
# 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 interactively

Warning: Rebasing rewrites history. Avoid rebasing branches that are shared with others, as it can cause significant problems.

Terminal window
# Cherry-pick a specific commit from another branch
git cherry-pick <commit_hash>
Terminal window
# Add a submodule
git submodule add <repository_url> <path>
# Initialize submodules after cloning
git submodule init
git submodule update
# Update submodules
git submodule update --remote

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 files
for 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
fi
done
exit 0

Make the script executable:

Terminal window
chmod +x .git/hooks/pre-commit

Git attributes allow you to define per-file attributes for your repository. They are defined in the .gitattributes file.

Terminal window
# 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=crlf

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.

Terminal window
# Create a new worktree
git worktree add <path> <branch>
# List all worktrees
git worktree list
# Remove a worktree
git worktree remove <path>
  • 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 bisect to 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 status
    git config --global alias.co checkout
    git config --global alias.br branch
    git config --global alias.ci commit
    git 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, and git lg.

  • Use git blame to see who changed a specific line: Helpful for tracking down the history of a particular line of code.

  • git clean -fd to remove untracked files and directories: Use with caution, as this is a destructive operation. Add -n for 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. Use git 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"

  • “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 add and git 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 --abort to cancel the rebase.
  • Accidentally committed sensitive data: Use git filter-branch or git rebase -i to remove the sensitive data from the history. This is a complex process, so research it thoroughly before attempting. Consider using tools like git-secrets to prevent accidental commits of sensitive data in the first place.
  • 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.