Git Aliases for Clean Commits

Today I'd love to introduce three useful Git aliases to maintain clean code and intelligent staging.

Quick Setup

# 1. Remove trailing whitespace from modified files
git config --global alias.cleanup '!git -c color.status=false status -s | grep -v "^D\|^.D" | cut -c4- | xargs -r -I {} sed -i "s/[[:space:]]*$//" {}'

# 2. Stage only substantive changes (ignore whitespace)  
git config --global alias.stagewhitespace '!git reset . && git add -N . && git diff -w -b | git apply --cached --ignore-whitespace'

# 3. Combine both operations
git config --global alias.smartadd '!git cleanup && git stagewhitespace'

Usage

git cleanup         # Clean trailing spaces only
git stagewhitespace # Stage content changes only
git smartadd        # Clean + smart staging

What Each Alias Does

cleanup

  • Removes trailing whitespace from all modified files
  • Skips deleted files to avoid errors
  • Handles ANSI color codes in git status output

stagewhitespace

  • Resets staging area
  • Marks new files as intent-to-add
  • Stages only meaningful content changes
  • Ignores pure whitespace modifications

smartadd

  • Runs cleanup first, then stagewhitespace
  • One command for clean, intelligent staging

Key Features

  • Safe: Filters out deleted files to prevent errors
  • Smart: Handles new files correctly
  • Clean: Maintains consistent code formatting
  • Focused: Stages only substantive changes

Technical Details

The aliases handle several edge cases:

  • ANSI color codes in git output (disabled with -c color.status=false)
  • Deleted files that would cause sed errors (filtered with grep -v "^D\|^.D")
  • New untracked files (handled with git add -N)
  • Empty file lists (handled with xargs -r)

Perfect for teams that want clean commits without manual whitespace management.

Comments

  1. Markdown is allowed. HTML tags allowed: <strong>, <em>, <blockquote>, <code>, <pre>, <a>.