`n

Git Command Line Workflow - Complete Guide

Published: September 25, 2024 | Reading time: 21 minutes

Git Workflow Overview

Master Git command line with essential workflows and advanced techniques:

Git Workflow Components
# Basic Git Operations
- git init, clone, add, commit
- git push, pull, fetch
- git branch, checkout, merge

# Advanced Operations
- git rebase, cherry-pick, stash
- git reset, revert, clean
- git log, diff, blame

Essential Git Commands

Repository Setup

Initial Setup
# Configure Git user
git config --global user.name "Your Name"
git config --global user.email "your.email@example.com"

# Initialize new repository
git init

# Clone existing repository
git clone https://github.com/user/repo.git
git clone https://github.com/user/repo.git my-project

# Clone specific branch
git clone -b feature-branch https://github.com/user/repo.git

# Clone with depth (shallow clone)
git clone --depth 1 https://github.com/user/repo.git

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

# List remotes
git remote -v

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

Basic Workflow

Daily Git Commands
# Check repository status
git status

# Add files to staging
git add file.txt
git add .                    # Add all files
git add *.js                 # Add all JS files
git add -A                   # Add all changes

# Commit changes
git commit -m "Add new feature"
git commit -am "Quick commit" # Add and commit modified files

# Push to remote
git push origin main
git push -u origin main      # Set upstream branch

# Pull latest changes
git pull origin main
git pull --rebase origin main

# Fetch without merging
git fetch origin

Branching Strategies

Branch Management

Branch Commands
# List branches
git branch                   # Local branches
git branch -r               # Remote branches
git branch -a               # All branches

# Create and switch to branch
git checkout -b feature/new-feature
git switch -c feature/new-feature  # Newer syntax

# Switch between branches
git checkout main
git switch main             # Newer syntax

# Delete branches
git branch -d feature-branch
git branch -D feature-branch # Force delete

# Delete remote branch
git push origin --delete feature-branch

# Rename branch
git branch -m old-name new-name

# Track remote branch
git checkout -b local-branch origin/remote-branch

Git Flow Workflow

Git Flow
# Initialize Git Flow
git flow init

# Start feature
git flow feature start new-feature

# Finish feature
git flow feature finish new-feature

# Start release
git flow release start 1.0.0

# Finish release
git flow release finish 1.0.0

# Start hotfix
git flow hotfix start bug-fix

# Finish hotfix
git flow hotfix finish bug-fix

# Manual Git Flow workflow
# Create feature branch
git checkout -b feature/user-authentication
# Work on feature...
git add .
git commit -m "Add user authentication"
git push origin feature/user-authentication
# Create pull request
# Merge to develop branch

Advanced Git Operations

Rebasing

Rebase Commands
# Rebase current branch onto main
git rebase main

# Interactive rebase (last 3 commits)
git rebase -i HEAD~3

# Interactive rebase (from specific commit)
git rebase -i abc1234

# Continue rebase after resolving conflicts
git rebase --continue

# Abort rebase
git rebase --abort

# Skip current commit during rebase
git rebase --skip

# Rebase with strategy
git rebase -X theirs main
git rebase -X ours main

# Rebase onto different branch
git rebase --onto main feature-branch feature-branch~2

Stashing

Stash Commands
# Stash current changes
git stash

# Stash with message
git stash push -m "Work in progress"

# Stash specific files
git stash push -m "Partial work" file1.txt file2.txt

# List stashes
git stash list

# Apply stash
git stash apply
git stash apply stash@{0}

# Pop stash (apply and remove)
git stash pop
git stash pop stash@{0}

# Show stash contents
git stash show stash@{0}

# Show stash diff
git stash show -p stash@{0}

# Drop stash
git stash drop stash@{0}

# Clear all stashes
git stash clear

History and Inspection

Git Log

Log Commands
# Basic log
git log

# One-line log
git log --oneline

# Graph log
git log --graph --oneline --all

# Log with file changes
git log --stat

# Log with patches
git log -p

# Log specific file
git log -- file.txt

# Log between commits
git log abc1234..def5678

# Log since date
git log --since="2024-01-01"

# Log until date
git log --until="2024-12-31"

# Log by author
git log --author="John Doe"

# Log with custom format
git log --pretty=format:"%h - %an, %ar : %s"

# Log with decorations
git log --decorate --graph --oneline

Git Diff

Diff Commands
# Working directory vs staging
git diff

# Staging vs last commit
git diff --staged
git diff --cached

# Working directory vs last commit
git diff HEAD

# Compare commits
git diff abc1234 def5678

# Compare branches
git diff main..feature-branch

# Compare with remote
git diff origin/main

# Diff specific file
git diff -- file.txt

# Diff with word-level changes
git diff --word-diff

# Diff with ignore whitespace
git diff -w

# Diff with context lines
git diff -U5

Undoing Changes

Reset Operations

Reset Commands
# Soft reset (keep changes in staging)
git reset --soft HEAD~1

# Mixed reset (keep changes in working directory)
git reset HEAD~1
git reset --mixed HEAD~1

# Hard reset (discard all changes)
git reset --hard HEAD~1

# Reset to specific commit
git reset --hard abc1234

# Reset specific file
git reset HEAD file.txt

# Reset to remote branch
git reset --hard origin/main

# Reset and keep changes
git reset --soft HEAD~1

# Unstage all files
git reset HEAD .

Revert Operations

Revert Commands
# Revert last commit
git revert HEAD

# Revert specific commit
git revert abc1234

# Revert without creating commit
git revert --no-commit abc1234

# Revert merge commit
git revert -m 1 abc1234

# Revert multiple commits
git revert abc1234 def5678

# Revert with custom message
git revert -m "Revert problematic feature" abc1234

Collaborative Workflows

Pull Requests and Merging

Merge Commands
# Merge branch into current branch
git merge feature-branch

# Merge with no fast-forward
git merge --no-ff feature-branch

# Merge with squash
git merge --squash feature-branch

# Merge with custom message
git merge -m "Merge feature branch" feature-branch

# Abort merge
git merge --abort

# Cherry-pick commit
git cherry-pick abc1234

# Cherry-pick multiple commits
git cherry-pick abc1234 def5678

# Cherry-pick range
git cherry-pick abc1234..def5678

# Cherry-pick without commit
git cherry-pick --no-commit abc1234

Conflict Resolution

Conflict Handling
# Check for conflicts
git status

# List conflicted files
git diff --name-only --diff-filter=U

# Resolve conflicts manually
# Edit conflicted files
# Remove conflict markers
# Stage resolved files
git add resolved-file.txt

# Continue merge/rebase
git commit
git rebase --continue

# Use merge tool
git mergetool

# Accept all changes from one side
git checkout --ours file.txt    # Keep current branch changes
git checkout --theirs file.txt  # Keep incoming changes

# Abort merge/rebase
git merge --abort
git rebase --abort

Git Hooks and Automation

Git Hooks

Hook Examples
# Pre-commit hook
#!/bin/bash
# .git/hooks/pre-commit
echo "Running pre-commit checks..."

# Run linter
npm run lint

# Run tests
npm test

# Check for TODO comments
if git diff --cached --name-only | xargs grep -l "TODO\|FIXME"; then
    echo "Warning: Found TODO/FIXME comments"
fi

# Pre-push hook
#!/bin/bash
# .git/hooks/pre-push
echo "Running pre-push checks..."

# Run full test suite
npm run test:full

# Check branch naming
current_branch=$(git rev-parse --abbrev-ref HEAD)
if [[ ! $current_branch =~ ^(feature|bugfix|hotfix)/ ]]; then
    echo "Error: Branch name must start with feature/, bugfix/, or hotfix/"
    exit 1
fi

# Post-commit hook
#!/bin/bash
# .git/hooks/post-commit
echo "Commit completed: $(git log -1 --pretty=format:'%h - %s')"

Git Aliases and Shortcuts

Useful Aliases

Git Aliases
# Add to ~/.gitconfig

[alias]
    # Basic shortcuts
    st = status
    co = checkout
    br = branch
    ci = commit
    unstage = reset HEAD --
    last = log -1 HEAD
    visual = !gitk

    # Enhanced commands
    lg = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)<%an>%Creset' --abbrev-commit
    ll = log --oneline --graph --decorate --all
    ls = log --stat
    lp = log -p

    # Branch management
    bd = branch -d
    bD = branch -D
    bm = branch -m
    ba = branch -a

    # Stash shortcuts
    save = stash push
    pop = stash pop
    list = stash list

    # Reset shortcuts
    uncommit = reset --soft HEAD~1
    unstage = reset HEAD --

    # Merge shortcuts
    mff = merge --ff-only
    mnf = merge --no-ff

    # Custom workflows
    cleanup = "!git branch --merged | grep -v '\\*\\|main\\|develop' | xargs -n 1 git branch -d"
    undo = reset HEAD~1
    amend = commit --amend --no-edit

Git Best Practices

Commit Guidelines

Commit Best Practices
# Good commit messages
git commit -m "Add user authentication feature"
git commit -m "Fix memory leak in data processing"
git commit -m "Update documentation for API changes"

# Bad commit messages
git commit -m "fix"
git commit -m "updates"
git commit -m "WIP"

# Commit message format
# (): 
# 
# 
# 
# 
# Examples: feat(auth): add OAuth2 integration fix(api): resolve timeout issues docs(readme): update installation instructions style(css): format code according to standards refactor(utils): extract common functions test(auth): add unit tests for login chore(deps): update dependencies # Atomic commits # Good: One logical change per commit git add src/auth/login.js git commit -m "feat(auth): implement login functionality" # Bad: Multiple unrelated changes git add . git commit -m "fix various issues"

Branch Naming

Branch Naming Conventions
# Feature branches
feature/user-authentication
feature/payment-integration
feature/dashboard-redesign

# Bug fix branches
bugfix/login-error
bugfix/memory-leak
bugfix/api-timeout

# Hotfix branches
hotfix/security-patch
hotfix/critical-bug

# Release branches
release/v1.2.0
release/v2.0.0

# Development branches
develop
main
master

# Personal branches
john/feature-branch
jane/bugfix-branch

# Issue-based branches
issue-123/fix-login-bug
issue-456/add-new-feature

Git Troubleshooting

Common Issues

Troubleshooting
# Recover deleted commits
git reflog
git checkout abc1234
git checkout -b recovered-branch

# Recover deleted files
git checkout HEAD -- deleted-file.txt

# Fix detached HEAD
git checkout -b new-branch-name

# Clean working directory
git clean -fd
git clean -fdx  # Include ignored files

# Fix corrupted repository
git fsck
git gc --prune=now

# Reset to remote state
git fetch origin
git reset --hard origin/main

# Fix merge conflicts
git status
git diff
# Edit conflicted files
git add resolved-files
git commit

# Fix rebase conflicts
git status
git diff
# Edit conflicted files
git add resolved-files
git rebase --continue

# Recover from bad rebase
git reflog
git reset --hard HEAD@{2}

Summary

Master Git command line workflow with these essential practices:

  • Learn basic commands: add, commit, push, pull, branch, merge
  • Use branching strategies: Git Flow, feature branches, pull requests
  • Master advanced operations: rebase, stash, cherry-pick, reset
  • Follow best practices: atomic commits, clear messages, proper naming
  • Use aliases and hooks: automate common tasks
  • Handle conflicts properly: understand merge vs rebase
  • Learn troubleshooting: reflog, recovery, conflict resolution

Need More Help?

Struggling with Git command line workflow or need help implementing proper version control practices? Our Git experts can help you master collaborative development workflows.

Get Git Help