restore Git Command Guide
The git restore command restores specified paths in the working tree with contents from a restore source. It can restore files from the index, HEAD, or any commit, and can operate on the working tree, index (staging area), or both.
git restore Syntax:
Section titled “git restore Syntax:”git restore [<options>] [--source=<tree>] [--staged] [--worktree] [--] <pathspec>...git restore [<options>] [--source=<tree>] [--staged] [--worktree] --pathspec-from-file=<file> [--pathspec-file-nul]git restore (-p|--patch) [<options>] [--source=<tree>] [--staged] [--worktree] [--] [<pathspec>...]Target Options:
Section titled “Target Options:”| Option | Description |
|---|---|
--staged | Restore from index to HEAD (unstages changes) |
--worktree | Restore from index to working tree (default) |
--staged --worktree | Restore both index and working tree |
Source Options:
Section titled “Source Options:”| Option | Description |
|---|---|
--source=<tree> | Restore from specified commit/tree (default: HEAD for —staged, index for —worktree) |
-s <tree> | Short form of —source |
Selection Options:
Section titled “Selection Options:”| Option | Description |
|---|---|
--patch, -p | Interactively select hunks to restore |
--pathspec-from-file=<file> | Read pathspec from file |
--pathspec-file-nul | Use NUL delimiter for pathspec file |
-q, --quiet | Suppress output |
--progress | Show progress |
--no-progress | Hide progress |
Parameters:
Section titled “Parameters:”| Parameter | Description |
|---|---|
<pathspec> | Files/directories to restore |
<tree> | Source commit/tree for restoration |
Understanding Restore Operations:
Section titled “Understanding Restore Operations:”Restore vs Other Commands:
Section titled “Restore vs Other Commands:”Command Comparison:├── git restore --worktree: Restore working tree (like git checkout <commit> <file>)├── git restore --staged: Unstage changes (like git reset HEAD <file>)├── git restore --staged --worktree: Reset file completely (like git checkout HEAD <file>)├── git checkout <file>: Older way to restore working tree├── git reset HEAD <file>: Older way to unstageRestore Sources:
Section titled “Restore Sources:”Available Sources:├── Index: Default for --worktree operations├── HEAD: Default for --staged operations├── Any commit: Specified with --source=<commit>├── Branch names: --source=main├── Relative refs: --source=HEAD~1└── Tree objects: Direct tree SHA-1Safe File Operations:
Section titled “Safe File Operations:”Restore Safety:├── Never affects branch history├── Only modifies working tree or index├── Preserves untracked files├── Can be undone with git checkout└── No risk of detached HEAD stateBasic Restore Examples:
Section titled “Basic Restore Examples:”Working Tree Restoration:
Section titled “Working Tree Restoration:”# Restore file to match index (discard working tree changes)git restore file.txt
# Restore multiple filesgit restore file1.txt file2.txt
# Restore directorygit restore src/
# Restore with patterngit restore "*.tmp"Index Restoration (Unstaging):
Section titled “Index Restoration (Unstaging):”# Unstage file (restore index to HEAD)git restore --staged file.txt
# Unstage multiple filesgit restore --staged file1.txt file2.txt
# Unstage all changesgit restore --staged .
# Unstage specific directorygit restore --staged src/Complete File Reset:
Section titled “Complete File Reset:”# Reset file completely (index + working tree to HEAD)git restore --staged --worktree file.txt
# Reset multiple filesgit restore --staged --worktree file1.txt file2.txt
# Reset entire directorygit restore --staged --worktree src/Advanced Restore Scenarios:
Section titled “Advanced Restore Scenarios:”Selective Restoration:
Section titled “Selective Restoration:”# Restore from specific commitgit restore --source=HEAD~1 file.txt
# Restore from different branchgit restore --source=main file.txt
# Restore from taggit restore --source=v1.0 file.txt
# Restore from specific commitgit restore --source=abc123 file.txtInteractive Restoration:
Section titled “Interactive Restoration:”# Interactively restore hunksgit restore --patch file.txt
# Interactively unstage hunksgit restore --patch --staged file.txt
# Choose hunks to restore# y: restore this hunk# n: do not restore this hunk# s: split into smaller hunks# q: quitBatch Operations:
Section titled “Batch Operations:”# Restore from file listgit restore --pathspec-from-file=files-to-restore.txt
# Restore with NUL delimitersgit restore --pathspec-from-file=files.txt --pathspec-file-nul
# Combine with findfind . -name "*.tmp" -print0 | xargs -0 git restoreConflict Resolution:
Section titled “Conflict Resolution:”# Restore conflicted file to pre-merge stategit restore --source=HEAD file.txt # Restore to our sidegit restore --source=MERGE_HEAD file.txt # Restore to their side
# Reset merge conflict markersgit restore --staged --worktree file.txt # Reset to HEAD
# Clean up after conflict resolutiongit restore --staged file.txt # Unstage resolved fileConfiguration and Best Practices:
Section titled “Configuration and Best Practices:”Git Configuration for Restore:
Section titled “Git Configuration for Restore:”# Configure restore behaviorgit config restore.default untracked # Handle untracked filesgit config restore.default ignored # Handle ignored files
# Configure progress displaygit config restore.progress truegit config restore.quiet falseSafe Restore Practices:
Section titled “Safe Restore Practices:”# Check what will be restoredgit statusgit diff file.txt # See working tree changesgit diff --staged file.txt # See staged changes
# Backup before complex restorescp file.txt file.txt.backup
# Verify restore resultgit statusgit diff file.txtRestore Strategy Guidelines:
Section titled “Restore Strategy Guidelines:”# Choose restore type based on situation:# - git restore file.txt: Discard working tree changes# - git restore --staged file.txt: Unstage changes# - git restore --staged --worktree file.txt: Complete reset# - git restore --source=<commit> file.txt: Restore from specific version
# General rule: Use --staged for unstaging, --worktree for discarding changesIntegration with Development Workflows:
Section titled “Integration with Development Workflows:”File State Management:
Section titled “File State Management:”#!/bin/bash# Safe file state management with restore
manage_file_state() { local file="$1" local action="$2"
case "$action" in "backup") # Create backup before changes cp "$file" "${file}.backup" echo "Backup created: ${file}.backup" ;; "restore") # Restore from backup if [ -f "${file}.backup" ]; then git restore "$file" mv "${file}.backup" "$file" echo "File restored from backup" else echo "No backup found" fi ;; "clean") # Clean up backup rm -f "${file}.backup" echo "Backup cleaned up" ;; esac}
manage_file_state "important.txt" "backup"# Make changes...manage_file_state "important.txt" "restore"Development Workflow Integration:
Section titled “Development Workflow Integration:”# Integrate restore into development workflowdevelopment_restore() { local branch="${1:-main}"
echo "Restoring development environment..."
# Stash current work git stash push -m "Pre-restore stash"
# Restore to clean branch state git restore --staged --worktree .
# Switch to target branch git checkout "$branch"
# Restore working directory git restore .
echo "Development environment restored"}
development_restore "feature-branch"Automated Cleanup:
Section titled “Automated Cleanup:”# Automated file cleanup with restoreautomated_cleanup() { echo "Performing automated cleanup..."
# Restore config files to repository versions git restore --staged --worktree "*.config" "*.ini" "*.json"
# Unstage generated files find . -name "*.generated" -exec git restore --staged {} \;
# Clean up temporary files find . -name "*.tmp" -exec git restore {} \;
echo "Automated cleanup complete"}
automated_cleanupTroubleshooting Common Issues:
Section titled “Troubleshooting Common Issues:”Unexpected File Changes:
Section titled “Unexpected File Changes:”# Check what restore will dogit statusgit diff file.txtgit diff --staged file.txt
# Preview restore impactgit restore --dry-run file.txt # If supported
# Recover from mistaken restoregit checkout HEAD file.txt # Restore from HEADgit checkout @ file.txt # Alternative syntaxRestore Conflicts:
Section titled “Restore Conflicts:”# Handle restore during merge conflictsresolve_restore_conflicts() { echo "Resolving restore conflicts..."
# Check conflict state git status
# Choose restore source git restore --source=HEAD file.txt # Restore to our version git restore --source=MERGE_HEAD file.txt # Restore to their version
# Mark as resolved git add file.txt}
resolve_restore_conflictsPermission and Access Issues:
Section titled “Permission and Access Issues:”# Handle permission issues during restorefix_restore_permissions() { echo "Fixing restore permission issues..."
# Check file permissions ls -la file.txt
# Fix ownership sudo chown $(whoami) file.txt
# Fix permissions chmod 644 file.txt
# Retry restore git restore file.txt}
fix_restore_permissionsLarge File Handling:
Section titled “Large File Handling:”# Handle large files efficientlyrestore_large_files() { echo "Restoring large files..."
# Check file sizes find . -type f -size +100M -exec ls -lh {} \;
# Restore large files individually find . -type f -size +100M -exec git restore {} \;
# Monitor progress echo "Large file restore complete"}
restore_large_filesReal-World Usage Examples:
Section titled “Real-World Usage Examples:”Code Review Preparation:
Section titled “Code Review Preparation:”# Prepare files for code reviewprepare_for_review() { echo "Preparing files for code review..."
# Unstage all changes git restore --staged .
# Restore working tree to HEAD git restore .
# Clean up untracked files git clean -fd
# Verify clean state git status
echo "Files prepared for review"}
prepare_for_reviewExperimental Changes Management:
Section titled “Experimental Changes Management:”# Manage experimental changes safelyexperimental_changes() { local file="$1"
echo "Managing experimental changes for $file..."
# Create backup cp "$file" "${file}.experimental"
# Make experimental changes # ... edit file ...
# Test changes if run_tests; then echo "✓ Experimental changes successful" # Keep changes else echo "✗ Experimental changes failed" # Restore original git restore "$file" echo "Original file restored" fi
# Clean up backup rm -f "${file}.experimental"}
experimental_changes "config.txt"Selective Commit Preparation:
Section titled “Selective Commit Preparation:”# Prepare selective commits with restoreselective_commit_prep() { echo "Preparing selective commit..."
# Stage all changes git add .
# Interactively unstage unwanted changes git restore --patch --staged
# Review staged changes git diff --staged
# Commit selected changes git commit -m "Selective commit"
echo "Selective commit prepared"}
selective_commit_prepRepository State Cleanup:
Section titled “Repository State Cleanup:”# Clean up repository staterepository_cleanup() { echo "Cleaning up repository state..."
# Restore tracked files to HEAD git restore --staged --worktree .
# Remove untracked files git clean -fd
# Reset submodules if any git submodule foreach git restore --staged --worktree .
# Verify clean state if [ -z "$(git status --porcelain)" ]; then echo "✓ Repository state cleaned" else echo "⚠ Some files still modified" git status fi}
repository_cleanupBackup and Recovery:
Section titled “Backup and Recovery:”# Backup and recovery with restorebackup_recovery_workflow() { local action="$1" local file="$2"
case "$action" in "backup") # Create backup before risky operations git restore --source=HEAD "$file" cp "$file" "${file}.backup" echo "Backup created for $file" ;; "restore") # Restore from backup if [ -f "${file}.backup" ]; then cp "${file}.backup" "$file" git add "$file" echo "File restored from backup" else echo "No backup found" fi ;; "cleanup") # Clean up backups find . -name "*.backup" -delete echo "Backups cleaned up" ;; esac}
backup_recovery_workflow "backup" "important.txt"# ... do risky operations ...backup_recovery_workflow "restore" "important.txt"backup_recovery_workflow "cleanup"What’s the difference between restore and checkout?
Section titled “What’s the difference between restore and checkout?”git restore is modern command for file operations; git checkout can also restore files but has multiple purposes and can accidentally create detached HEAD.
How do I unstage a file with restore?
Section titled “How do I unstage a file with restore?”git restore —staged
Can I restore a file from a specific commit?
Section titled “Can I restore a file from a specific commit?”Yes, git restore —source=
What’s the difference between restore and reset?
Section titled “What’s the difference between restore and reset?”restore operates on files without changing branch history; reset changes branch pointers and can affect multiple commits.
How do I discard working tree changes?
Section titled “How do I discard working tree changes?”git restore
Can I restore multiple files at once?
Section titled “Can I restore multiple files at once?”Yes, git restore file1.txt file2.txt or git restore *.txt for pattern matching.
How do I restore a deleted file?
Section titled “How do I restore a deleted file?”git restore
What’s the safest way to use restore?
Section titled “What’s the safest way to use restore?”Always check git status first, use —staged for unstaging, and create backups for important files.
Can restore work with directories?
Section titled “Can restore work with directories?”Yes, git restore
How do I preview what restore will do?
Section titled “How do I preview what restore will do?”Check git status and git diff to see current changes before using restore.
Can I restore from a remote branch?
Section titled “Can I restore from a remote branch?”Yes, git restore —source=origin/main
What’s the difference between restore and revert?
Section titled “What’s the difference between restore and revert?”restore affects individual files; revert creates new commits that undo changes to multiple files.
How do I restore a file to a previous version?
Section titled “How do I restore a file to a previous version?”git restore —source=
Can restore handle binary files?
Section titled “Can restore handle binary files?”Yes, restore works with all file types, including binary files.
How do I restore all files in working tree?
Section titled “How do I restore all files in working tree?”git restore . restores all files in current directory recursively.
Can I use restore in scripts?
Section titled “Can I use restore in scripts?”Yes, restore is script-friendly with predictable behavior and clear exit codes.
Applications of the git restore command
Section titled “Applications of the git restore command”- File State Management: Safely restore files to previous states without affecting branch history
- Staging Area Control: Unstage files and changes selectively before committing
- Working Tree Cleanup: Discard unwanted changes and restore clean file states
- Commit Preparation: Prepare selective commits by unstaging unwanted changes
- Conflict Resolution: Restore files during merge conflict resolution
- Development Workflow: Manage experimental changes and file backups safely