Skip to content
Home » Git Command Line Complete Guide for Mac Users

Git Command Line Complete Guide for Mac Users

  • by

Git is an essential tool for modern developers, and mastering Git command line operations on Mac is crucial for efficient version control and collaboration. This comprehensive guide covers everything from basic installation to advanced techniques, SSH key configuration, and repository management.

Table of Contents

Installing Git on Mac

Method 1: Xcode Command Line Tools (Recommended for Beginners)

The easiest way to install Git is through Xcode Command Line Tools:

# Check if Git is already installed
git --version

# If not installed, this command will prompt installation
xcode-select --install

If Git isn’t installed, you’ll see a dialog asking if you want to install Command Line Tools. Click “Install” and follow the prompts.

Method 2: Homebrew (Recommended for Developers)

Homebrew often provides more up-to-date versions:

# Install Homebrew if you haven't already
/bin/bash -c "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/HEAD/install.sh)"

# Install Git via Homebrew
brew install git

# Verify installation
git --version

Method 3: Official Git Installer

Download the latest macOS Git installer from git-scm.com and follow the installation wizard.

Initial Git Configuration

After installing Git, you need to configure your identity:

Setting Up User Information

# Set your name (use your real name for professional projects)
git config --global user.name "Your Full Name"

# Set your email (use the same email as your GitHub account)
git config --global user.email "[email protected]"

# Verify your configuration
git config --global --list

Configuring Default Branch Name

# Set default branch name to 'main'
git config --global init.defaultBranch main

Setting Up Credential Helper

To avoid entering passwords repeatedly:

# Use macOS Keychain for credential storage
git config --global credential.helper osxkeychain

SSH Key Setup for GitHub

SSH keys provide secure, password-less authentication to GitHub.

Checking for Existing SSH Keys

# List existing SSH keys
ls -la ~/.ssh

# Look for files like id_rsa.pub, id_ed25519.pub, etc.

Generating a New SSH Key

# Generate SSH key (replace with your GitHub email)
ssh-keygen -t ed25519 -C "[email protected]"

# For older systems that don't support Ed25519:
ssh-keygen -t rsa -b 4096 -C "[email protected]"

When prompted:

  • File location: Press Enter for default (~/.ssh/id_ed25519)
  • Passphrase: Optional but recommended for security

Adding SSH Key to ssh-agent

# Start ssh-agent
eval "$(ssh-agent -s)"

# Create or modify SSH config file
touch ~/.ssh/config
open ~/.ssh/config

Add this configuration to ~/.ssh/config:

Host github.com
  AddKeysToAgent yes
  UseKeychain yes
  IdentityFile ~/.ssh/id_ed25519
# Add SSH key to ssh-agent and keychain
ssh-add --apple-use-keychain ~/.ssh/id_ed25519

Adding SSH Key to GitHub

# Copy public key to clipboard
pbcopy < ~/.ssh/id_ed25519.pub

# Or display the key to copy manually
cat ~/.ssh/id_ed25519.pub
  1. Go to GitHub.com → Settings → SSH and GPG keys
  2. Click "New SSH key"
  3. Add a descriptive title (e.g., "MacBook Pro")
  4. Paste your public key
  5. Click "Add SSH key"

Testing SSH Connection

# Test SSH connection to GitHub
ssh -T [email protected]

You should see: "Hi [username]! You've successfully authenticated, but GitHub does not provide shell access."

Basic Git Commands

Repository Initialization

# Initialize a new repository
git init

# Clone an existing repository
git clone [email protected]:username/repository.git

# Clone with a different directory name
git clone [email protected]:username/repository.git my-project

Working with Files

# Check repository status
git status

# Add files to staging area
git add filename.txt          # Add specific file
git add .                     # Add all files
git add *.js                  # Add all JavaScript files

# Remove files from staging area
git reset filename.txt        # Unstage specific file
git reset                     # Unstage all files

# Commit changes
git commit -m "Your commit message"

# Add and commit in one command
git commit -am "Add and commit message"

Viewing History

# View commit history
git log
git log --oneline             # Condensed view
git log --graph               # ASCII graph
git log -p                    # Show changes

# View specific number of commits
git log -5                    # Last 5 commits

# View changes
git diff                      # Working directory vs staging
git diff --staged             # Staging vs last commit
git diff HEAD~1               # Compare with previous commit

Repository Management

Remote Repositories

# View remote repositories
git remote -v

# Add remote repository
git remote add origin [email protected]:username/repository.git

# Change remote URL
git remote set-url origin [email protected]:username/new-repo.git

# Remove remote
git remote remove origin

Synchronizing with Remote

# Fetch changes from remote
git fetch origin

# Pull changes (fetch + merge)
git pull origin main

# Push changes to remote
git push origin main

# Push and set upstream branch
git push -u origin main

# Force push (use with caution)
git push --force-with-lease origin main

Branching and Merging

Branch Management

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

# Create new branch
git branch feature-branch

# Switch to branch
git checkout feature-branch

# Create and switch to new branch
git checkout -b feature-branch

# Modern syntax (Git 2.23+)
git switch feature-branch     # Switch to existing branch
git switch -c feature-branch  # Create and switch to new branch

Merging Branches

# Switch to target branch
git checkout main

# Merge feature branch
git merge feature-branch

# Merge with no-fast-forward (preserves branch history)
git merge --no-ff feature-branch

# Abort merge if conflicts
git merge --abort

Deleting Branches

# Delete local branch (safe)
git branch -d feature-branch

# Force delete local branch
git branch -D feature-branch

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

Advanced Git Techniques

Stashing Changes

# Stash current changes
git stash

# Stash with message
git stash save "Work in progress on feature X"

# List stashes
git stash list

# Apply most recent stash
git stash apply

# Apply and remove stash
git stash pop

# Apply specific stash
git stash apply stash@{2}

# Drop stash
git stash drop stash@{0}

# Clear all stashes
git stash clear

Rewriting History

# Amend last commit
git commit --amend -m "New commit message"

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

# Squash commits
git rebase -i HEAD~3  # Then change 'pick' to 'squash'

# Reset to previous commit
git reset --soft HEAD~1   # Keep changes staged
git reset --mixed HEAD~1  # Keep changes unstaged (default)
git reset --hard HEAD~1   # Discard changes completely

Cherry-picking

# Apply specific commit to current branch
git cherry-pick <commit-hash>

# Cherry-pick multiple commits
git cherry-pick <commit1> <commit2>

# Cherry-pick without committing
git cherry-pick --no-commit <commit-hash>

Working with Tags

# List tags
git tag

# Create lightweight tag
git tag v1.0.0

# Create annotated tag
git tag -a v1.0.0 -m "Version 1.0.0 release"

# Tag specific commit
git tag -a v1.0.0 <commit-hash> -m "Version 1.0.0"

# Push tags to remote
git push origin v1.0.0       # Push specific tag
git push origin --tags       # Push all tags

# Delete tag
git tag -d v1.0.0            # Delete local tag
git push origin --delete v1.0.0  # Delete remote tag

Advanced Searching

# Search in files
git grep "search term"

# Search in specific file types
git grep "function" -- "*.js"

# Search in commit messages
git log --grep="bug fix"

# Search in commit content
git log -S "function_name"

# Find when a line was added/modified
git blame filename.txt

# Find commits that changed a specific line
git log -L 15,20:filename.txt

Troubleshooting Common Issues

Authentication Issues

# If SSH authentication fails, check:
ssh-add -l                    # List SSH keys in agent
ssh-add ~/.ssh/id_ed25519     # Re-add key if missing

# For HTTPS authentication issues:
git config --global credential.helper osxkeychain

Merge Conflicts

# When merge conflicts occur:
git status                    # See conflicted files
# Edit files to resolve conflicts
git add .                     # Stage resolved files
git commit                    # Complete the merge

# Or abort the merge:
git merge --abort

Undoing Changes

# Discard changes in working directory
git checkout -- filename.txt

# Unstage file
git reset HEAD filename.txt

# Undo last commit but keep changes
git reset --soft HEAD~1

# Completely remove last commit
git reset --hard HEAD~1

# Revert commit (creates new commit)
git revert <commit-hash>

Cleaning Repository

# Remove untracked files (dry run)
git clean -n

# Remove untracked files
git clean -f

# Remove untracked files and directories
git clean -fd

# Remove ignored files too
git clean -fX

Best Practices

Commit Messages

Follow conventional commit format:

  • feat: add new feature
  • fix: resolve bug in user authentication
  • docs: update README with installation instructions
  • style: fix code formatting
  • refactor: reorganize utility functions
  • test: add unit tests for user service

Branch Naming

Use descriptive branch names:

  • feature/user-authentication
  • bugfix/login-error
  • hotfix/security-patch
  • docs/api-documentation

Security Considerations

  1. Never commit sensitive data (passwords, API keys, personal information)
  2. Use SSH keys instead of passwords for GitHub authentication
  3. Set up .gitignore properly to exclude sensitive files
  4. Regularly update Git to the latest version
  5. Use signed commits for important repositories

Performance Tips

# Speed up Git operations
git config --global core.preloadindex true
git config --global core.fscache true
git config --global gc.auto 256

# Enable parallel processing
git config --global submodule.fetchJobs 4

Conclusion

This comprehensive guide covers the essential Git command line operations for Mac users. From basic installation and configuration to advanced techniques like rebasing and cherry-picking, these commands form the foundation of effective version control.

Remember to practice these commands in a test repository before using them on important projects. Git's power comes with responsibility – always make sure you understand what a command does before executing it, especially commands that modify history.

For continued learning, explore Git's extensive documentation with git help <command> or visit the official Git documentation at git-scm.com.

Key Takeaways:

  • Set up SSH keys for secure, password-less authentication
  • Use meaningful commit messages and branch names
  • Understand the difference between local and remote operations
  • Practice safe history rewriting techniques
  • Keep your Git installation and knowledge up to date

Master these Git command line operations, and you'll be well-equipped to handle any version control challenge in your development workflow.

Leave a Reply

Your email address will not be published. Required fields are marked *