Operations 11 min read

How to Back Up and Migrate WSL Without Losing Your Development Environment

This guide walks you through exporting and importing WSL distributions, automating backups with PowerShell, managing dotfiles via a bare Git repository, using a migration checklist, and running one‑click scripts so you can switch computers or reinstall systems without losing any configuration or data.

Ubuntu
Ubuntu
Ubuntu
How to Back Up and Migrate WSL Without Losing Your Development Environment

Why backup and migrate?

Switching to a new computer – need to move the entire development environment.

Reinstalling the OS – avoid re‑configuring from scratch.

Team sharing – replicate the same environment for colleagues.

Data safety – prevent accidental loss.

Experiment snapshots – keep specific states for testing.

Core commands: wsl --export / --import

Basic syntax

# Export (backup)
wsl --export <distribution-name> <output-file-path>

# Import (restore/migrate)
wsl --import <new-distribution-name> <install-location> <tar-file-path>

Full example

# ===== Backup (export) =====
wsl --shutdown                     # Shut down all instances first
wsl --export Ubuntu-24.04 D:\backup\ubuntu2404-full.tar   # Export to tar
# Output: Export may take a few minutes; tar appears in D:\backup

# ===== Restore (import) to new location =====
wsl --import MyUbuntu D:\WSL\MyUbuntu D:\backup\ubuntu2404-full.tar
# Now you can use: wsl -d MyUbuntu

# ===== Verify =====
wsl --list -v   # Should show MyUbuntu in the list
--export includes user data, installed packages, configuration files, and project code. Resulting tar size typically ranges from 1 GB to over 10 GB depending on installed content. --unregister permanently deletes the original distribution; ensure a backup exists before using it.

Automated backup script (PowerShell)

Scheduled backup script

# Save as C:\Scripts\wsl-backup.ps1
param(
    [string]$BackupRoot = "D:\WSL-Backups",
    [string[]]$Distros = @("Ubuntu-24.04", "Debian")
)
$Timestamp = Get-Date -Format "yyyyMMdd_HHmmss"
$BackupDir = Join-Path $BackupRoot $Timestamp
New-Item -ItemType Directory -Path $BackupDir -Force | Out-Null
Write-Host "📦 Starting WSL backup → $BackupDir" -ForegroundColor Cyan
wsl --shutdown
Start-Sleep -Seconds 5
foreach ($Distro in $Distros) {
    $TarFile = Join-Path $BackupDir "$Distro.tar"
    Write-Host "📥 Backing up $Distro ..." -ForegroundColor Green
    try {
        wsl --export $Distro $TarFile
        $SizeMB = [math]::Round((Get-Item $TarFile).Length / 1MB, 1)
        Write-Host "   ✅ Completed! Size: $SizeMB MB" -ForegroundColor Green
        # Keep only the most recent 3 backups
        $OldBackups = Get-ChildItem "$BackupRoot\*\$Distro.tar" -ErrorAction SilentlyContinue |
            Sort-Object LastWriteTime -Descending | Select-Object -Skip 3
        foreach ($Old in $OldBackups) { Remove-Item $Old.FullName -Force }
    } catch { Write-Host "   ❌ Backup failed: $_" -ForegroundColor Red }
}
Copy-Item "$env:USERPROFILE\.wslconfig" "$BackupDir\wslconfig.backup" -ErrorAction SilentlyContinue
Write-Host "
🎉 Backup finished! Location: $BackupDir" -ForegroundColor Cyan
Get-ChildItem $BackupDir | ForEach-Object { "{0} ({1:N0} MB)" -f $_.Name, ($_.Length/1MB) }

Windows scheduled task

$action = New-ScheduledTaskAction -Execute "powershell.exe" -Argument "-ExecutionPolicy Bypass -File C:\Scripts\wsl-backup.ps1"
$trigger = New-ScheduledTaskTrigger -Weekly -DaysOfWeek Sunday -At 2am
$settings = New-ScheduledTaskSettingsSet -AllowStartIfOnBatteries -DontStopIfGoingOnBatteries
Register-ScheduledTask -TaskName "WSL Weekly Backup" -Action $action -Trigger $trigger -Settings $settings -Description "WSL automated backup task"

Dotfiles unified management (bare Git repository)

Manage only configuration files instead of a full tar export.

Typical dotfiles

# Hidden configuration files
~/.bashrc      # Shell config
~/.vimrc       # Vim config
~/.gitconfig   # Git config
~/.ssh/        # SSH keys
~/.config/     # Application configs
~/.wslconf     # WSL internal config

Git bare repository workflow

# Initialize bare repo
git init --bare $HOME/.cfg
alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'

# Add and commit all configs
config add ~/.bashrc ~/.vimrc ~/.gitconfig ~/.wslconf ~/.config/
config commit -m "initial dotfiles backup"

# Push to remote
config remote add origin [email protected]:user/dotfiles.git
config push -u origin main

Restore on a new machine

# Clone the bare repo
git init --bare $HOME/.cfg
alias config='/usr/bin/git --git-dir=$HOME/.cfg/ --work-tree=$HOME'
config remote add origin [email protected]:user/dotfiles.git
config pull origin main

# Install packages listed in a file (optional)
sudo apt update && sudo apt install -y $(cat ~/packages.txt)

Full migration checklist

WSL Environment Migration Checklist

A Computer – Backup Phase
1. Export distribution: wsl --export > backup.tar
2. Backup .wslconfig
3. Backup SSH keys (if needed)
4. Record installed package list
5. Record custom shell aliases/functions
6. (Optional) Backup Docker images and volumes
7. (Optional) Backup database data

B Computer – Restore Phase
8. Install WSL: wsl --install
9. Install Windows Terminal
10. Copy .wslconfig to user directory
11. Import distribution: wsl --import
12. Start and verify: wsl -d <name>
13. Switch to domestic mirror sources
14. Update system: apt update && apt upgrade
15. Install Nerd Font
16. Install VS Code + Remote‑WSL extension
17. Install Docker Desktop and configure WSL backend
18. Test Git and SSH connections
19. Verify Python/Node.js/Go environments
20. Start database services and verify connections

Verification Phase
21. Run projects to confirm functionality
22. Git push/pull passes
23. Docker builds and runs correctly
24. GPU available (if required)

One‑click environment restore script (Bash)

#!/bin/bash
set -e
echo "🚀 WSL new environment initialization script"

echo "📦 [1/6] Updating system..."
sudo apt update && sudo apt upgrade -y

echo "🔧 [2/6] Installing basic tools..."
sudo apt install -y git curl wget vim tree htop jq unzip zip \
    ca-certificates gnupg lsb-release software-properties-common \
    build-essential python3-pip python3-venv python3-dev

echo "🤖 [3/6] Installing Oh My Posh..."
wget https://github.com/JanDeDobbeleer/oh-my-posh/releases/latest/download/posh-linux-amd64 \
    -O /usr/local/bin/oh-my-posh && chmod +x /usr/local/bin/oh-my-posh

echo "🐍 [4/6] Python toolchain..."
pip install --upgrade pip uv ruff black mypy pytest httpie

echo "🔑 [5/6] Configuring Git..."
if [ ! -f ~/.gitconfig ]; then
    read -p "Git username: " GIT_NAME
    read -p "Git email: " GIT_EMAIL
    git config --global user.name "$GIT_NAME"
    git config --global user.email "$GIT_EMAIL"
    git config --global core.autocrlf input
fi

echo "✅ [6/6] All done!"
echo "Next manual steps:"
echo "  • Node.js (fnm)"
echo "  • Go (official installer)"
echo "  • Rust (rustup)"
echo "  • Docker Desktop"
echo "  • VS Code extensions"

Advanced multi‑machine sync solutions

Full backup : use wsl --export / --import for computer swaps or reinstallations.

Dotfiles : store configuration files in a Git bare repository (optionally with stow for symlink management).

Containerization : define a DevContainer or Dockerfile to provide a uniform environment for a team.

Cloud sync : sync small configuration directories via OneDrive or Dropbox.

Scripted setup : keep a one‑click setup script that installs system packages, tools, and restores dotfiles.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

MigrationAutomationbackupWSLpowershellDotfiles
Ubuntu
Written by

Ubuntu

Focused on Ubuntu/Linux tech sharing, offering the latest news, practical tools, beginner tutorials, and problem solutions. Connecting open-source enthusiasts to build a Linux learning community. Join our QQ group or channel for discussion!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.