Resetting a Broken Browser Without Losing Your Bookmarks
Two interactive scripts, PowerShell for Windows and Bash for macOS, that back up your bookmarks and passwords, move the browser profile aside instead of deleting it, and can put the old one back with one keypress.
Every so often a browser just gets weird. Pages won't load, extensions break, settings won't stick, or it crawls even after you clear the cache. When nothing else works, the fix that actually works is a fresh profile. The problem is that a fresh profile also means losing your bookmarks and saved passwords if you don't back them up first, and most people find that out after the fact.
I got tired of walking people through the same steps by hand, so I wrote a pair of interactive scripts that do it safely: one in PowerShell for Windows, and one in Bash for macOS. They walk you through exporting your bookmarks and passwords, check that the exports are actually there, then move the old profile out of the way instead of deleting it. If the reset doesn't help, one keypress puts everything back the way it was.
What It Does
- Pick a browser. Edge, Chrome or Firefox on Windows, plus Safari on the Mac. Each one shows whether it's installed, running, or has no profile yet.
- Back up. It opens the browser if it isn't running, prints the export steps, and can open the right settings page for you (
edge://favorites,chrome://password-manager/settings,about:loginsand so on). - Check the exports. It looks in Documents (and OneDrive's Documents, if that's a different folder) for each browser's default export file names saved today. Older exports are listed, but it warns you they may be missing recent changes.
- Explain the impact. Before touching anything, it lists what comes back (bookmarks and passwords) and what doesn't (tabs, history, cookies, site sign-ins, site permissions, autofill and settings), along with every folder it's about to rename and how big it is.
- Close and reset. It closes the browser, then renames its data folders to
.bak. - Relaunch and restore. The browser opens with a clean profile, and the script shows the import steps for your bookmarks and passwords.
- Keep or revert. If the problem is fixed, keep the new profile. If not, it renames the new one to
.tmpand puts the.bakback. - Summary. Sizes before and after, the start and finish times, and every folder that was renamed.
Nothing Gets Deleted
The main rule I designed around: a reset should never be the thing that loses your data. So the scripts only rename folders:
- The profile becomes
User Data.bak(orFirefox.bak,Safari.bakand so on). If a.bakalready exists, the new one gets a timestamp (.bak.20261130-101500) instead of overwriting it. - Run it again later and it finds the earlier backups. You can keep them, send them to the Recycle Bin or Trash (where they can still be recovered), or skip the reset and restore one of them instead.
- If a folder can't be renamed partway through, it stops and tells you exactly which ones were already renamed and how to undo them.
Firefox and the Chromium browsers keep caches in a second location, so those get renamed alongside the profile. Safari is spread across four places on the Mac: ~/Library/Safari, its container, its cache and its preferences plist.
Closing the Browser Cleanly
Renaming a profile while the browser still has it open either fails or corrupts it, so closing it properly mattered more than I expected:
- Windows: It asks each window to close, the same as clicking the X, and keeps asking for up to 10 seconds, since closing one window only closes that window. Edge's startup boost and Chrome's background apps leave windowless processes behind; with no tabs open those are safe to end, so the script ends them. If a window is still open after 20 seconds (usually a "leave page?" dialog), it asks before force quitting.
- macOS: It tells the app to quit through AppleScript, waits up to 20 seconds, then asks before force quitting.
- Both only touch processes owned by the current user, so another person signed in to the same PC is left alone.
Running It
Windows: download ResetBrowserLocal.ps1 and Reset_Browser.cmd into the same folder, then double-click Reset_Browser.cmd. It starts PowerShell with the execution policy bypassed for just that one run, so you don't have to change any system settings. It works in Windows PowerShell 5.1 and PowerShell 7, and it refuses to run as administrator, because the profile it resets belongs to whoever is signed in.
macOS: download ResetBrowserLocal.sh, then in Terminal:
cd ~/Downloads
bash ResetBrowserLocal.sh
To reset Safari, Terminal needs Full Disk Access (System Settings › Privacy & Security › Full Disk Access). Without it, macOS blocks the rename, and the script tells you so. Safari passwords live in the Passwords app and Keychain, so the reset doesn't touch them at all.
One reminder the scripts also give you: exported password .csv files aren't encrypted. Delete them as soon as you've imported them again.
The Scripts
Windows launcher
@echo off
rem Double-click launcher for ResetBrowserLocal.ps1 (keep both files in the same folder).
powershell.exe -NoProfile -ExecutionPolicy Bypass -File "%~dp0ResetBrowserLocal.ps1"
pause
Windows (PowerShell)
<#
ResetBrowserLocal.ps1 - interactive browser reset for this PC.
Walks you through: pick a browser > back up bookmarks and passwords > close the browser >
check the exports are in Documents > rename its data folder(s) to '.bak' > relaunch it >
restore your bookmarks and passwords > optionally revert to the old profile > summary.
Nothing is deleted. Reverting renames the new profile to '.tmp' and the '.bak' back.
Usage: powershell -NoProfile -ExecutionPolicy Bypass -File .\ResetBrowserLocal.ps1
(or double-click Reset_Browser.cmd in File Explorer)
Works in Windows PowerShell 5.1 and PowerShell 7.
#>
Set-StrictMode -Version 1.0 # like 'set -u': using an unset variable is an error
$E = [char]27
if ($Host.UI.SupportsVirtualTerminal) {
$BOLD = "${E}[1m"; $DIM = "${E}[2m"; $RED = "${E}[31m"; $GREEN = "${E}[32m"; $YELLOW = "${E}[33m"; $CYAN = "${E}[36m"; $RESET = "${E}[0m"
} else {
$BOLD = ''; $DIM = ''; $RED = ''; $GREEN = ''; $YELLOW = ''; $CYAN = ''; $RESET = ''
}
$BakSuffix = '.bak'
$TmpSuffix = '.tmp'
$CloseTimeoutSec = 20
$Browsers = @('edge', 'chrome', 'firefox')
$SessionId = (Get-Process -Id $PID).SessionId # only touch browser processes in this user's session
# Set by the steps below
$Browser = $null; $BrowserName = $null
$Backups = @(); $Originals = @(); $Tmps = @()
$Reverted = 'no'; $StaleExports = @(); $SizeBefore = 0; $Started = $null
# ------------------------------------------------------------------------------------- browser info
function Get-DisplayName([string]$key) {
switch ($key) { 'edge' { 'Microsoft Edge' } 'chrome' { 'Google Chrome' } 'firefox' { 'Mozilla Firefox' } }
}
function Get-ProcessName([string]$key) { # process name, without .exe
switch ($key) { 'edge' { 'msedge' } 'chrome' { 'chrome' } 'firefox' { 'firefox' } }
}
function Get-DataPaths([string]$key) { # profile folder first, then caches
switch ($key) {
'edge' { "$env:LOCALAPPDATA\Microsoft\Edge\User Data" }
'chrome' { "$env:LOCALAPPDATA\Google\Chrome\User Data" }
'firefox' { "$env:APPDATA\Mozilla\Firefox"; "$env:LOCALAPPDATA\Mozilla\Firefox" }
}
}
function Get-ExePath([string]$key) { # full path to the browser's .exe, or $null if not installed
$exe = "$(Get-ProcessName $key).exe"
$appPaths = @(
"HKCU:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\$exe",
"HKLM:\SOFTWARE\Microsoft\Windows\CurrentVersion\App Paths\$exe",
"HKLM:\SOFTWARE\WOW6432Node\Microsoft\Windows\CurrentVersion\App Paths\$exe"
)
foreach ($regKey in $appPaths) {
$value = (Get-ItemProperty -LiteralPath $regKey -ErrorAction SilentlyContinue).'(default)'
if ($value) {
$value = $value.Trim('"')
if (Test-Path -LiteralPath $value -PathType Leaf) { return $value }
}
}
$pf86 = ${env:ProgramFiles(x86)}
$candidates = switch ($key) {
'edge' { "$pf86\Microsoft\Edge\Application\msedge.exe"; "$env:ProgramFiles\Microsoft\Edge\Application\msedge.exe" }
'chrome' { "$env:ProgramFiles\Google\Chrome\Application\chrome.exe"; "$pf86\Google\Chrome\Application\chrome.exe"
"$env:LOCALAPPDATA\Google\Chrome\Application\chrome.exe" }
'firefox' { "$env:ProgramFiles\Mozilla Firefox\firefox.exe"; "$pf86\Mozilla Firefox\firefox.exe" }
}
foreach ($c in @($candidates)) { if (Test-Path -LiteralPath $c -PathType Leaf) { return $c } }
return $null
}
# Browser pages used in the steps: "label|address". They are opened by passing the address to the
# browser's .exe, because Windows has no handler for chrome://, edge:// or about: addresses.
function Get-BackupLinks([string]$key) {
switch ($key) {
'edge' { 'Favorites|edge://favorites'; 'Passwords|edge://settings/autofill/passwords' }
'chrome' { 'Bookmarks|chrome://bookmarks'; 'Passwords|chrome://password-manager/settings' }
'firefox' { 'Passwords|about:logins' }
}
}
function Get-RestoreLinks([string]$key) {
switch ($key) {
'edge' { 'Favorites|edge://favorites'; 'Passwords|edge://settings/autofill/passwords' }
'chrome' { 'Bookmarks|chrome://bookmarks'; 'Passwords|chrome://password-manager/settings' }
'firefox' { 'Passwords|about:logins' }
}
}
function Test-Installed([string]$key) { [bool](Get-ExePath $key) }
function Get-BrowserProcesses([string]$key) {
Get-Process -Name (Get-ProcessName $key) -ErrorAction SilentlyContinue | Where-Object { $_.SessionId -eq $SessionId }
}
function Test-Running([string]$key) { @(Get-BrowserProcesses $key).Count -gt 0 }
function Test-HasData([string]$key) { Test-Path -LiteralPath (@(Get-DataPaths $key)[0]) }
function Show-BackupSteps([string]$key) {
switch ($key) {
'edge' { Write-Host @'
Favorites: open edge://favorites > More options (...) > Export favorites
Save the .html file to Documents.
Passwords: open edge://settings/autofill/passwords > (...) > Export passwords
Save the .csv file to Documents.
'@ }
'chrome' { Write-Host @'
Bookmarks: open chrome://bookmarks > three dots (top right) > Export bookmarks
Save the .html file to Documents.
Passwords: open chrome://password-manager/settings > Export passwords > Download file
Save the .csv file to Documents.
'@ }
'firefox' { Write-Host @'
Bookmarks: Ctrl+Shift+O > Import and Backup > Export Bookmarks to HTML
Save the .html file to Documents.
Passwords: open about:logins > three dots (...) > Export Passwords
Save the .csv file to Documents.
'@ }
}
}
function Show-RestoreSteps([string]$key) {
switch ($key) {
'edge' { Write-Host @'
1. Favorites: open edge://favorites > More options (...) > Import favorites
> "Favorites or bookmarks HTML file" > choose your .html file.
2. Passwords: open edge://settings/autofill/passwords > (...) > Import passwords
> choose your .csv file.
'@ }
'chrome' { Write-Host @'
1. Bookmarks: open chrome://bookmarks > three dots (top right) > Import bookmarks
> choose your .html file (they appear in an "Imported" folder).
2. Passwords: open chrome://password-manager/settings > Import passwords > Select file
> choose your .csv file.
'@ }
'firefox' { Write-Host @'
1. Bookmarks: Ctrl+Shift+O > Import and Backup > Import Bookmarks from HTML
> choose your .html file.
2. Passwords: open about:logins > three dots (...) > Import from a File > choose your .csv file.
'@ }
}
}
# ------------------------------------------------------------------------------------------ helpers
function Show-Header([string]$title) { Write-Host ''; Write-Host "$BOLD$CYAN== $title ==$RESET"; Write-Host '' }
function Confirm-Yes([string]$question) { # $true for yes
while ($true) {
$answer = Read-Host "$question [y/n]"
if ($null -eq $answer) { exit 1 }
$answer = $answer.Trim().ToLowerInvariant()
if ($answer -eq 'y' -or $answer -eq 'yes') { return $true }
if ($answer -eq 'n' -or $answer -eq 'no') { return $false }
}
}
function Stop-Script([string]$reason) { # abort: nothing was changed
Write-Host ''
Write-Host "${YELLOW}Stopped: $reason$RESET"
Write-Host 'Nothing was changed.'
exit 0
}
function Get-FreeName([string]$path, [string]$suffix) { # never overwrites an existing folder
if (-not (Test-Path -LiteralPath "$path$suffix")) { return "$path$suffix" }
return "$path$suffix.$(Get-Date -Format 'yyyyMMdd-HHmmss')"
}
function Get-BackupName([string]$path) { Get-FreeName $path $BakSuffix }
function Get-ExportFolders { # Documents (follows OneDrive redirection), plus OneDrive's Documents if different
$seen = @{}
$candidates = @([Environment]::GetFolderPath('MyDocuments'))
foreach ($od in @($env:OneDrive, $env:OneDriveConsumer)) {
if ($od) { $candidates += (Join-Path $od 'Documents') }
}
foreach ($d in $candidates) {
if (-not $d -or -not (Test-Path -LiteralPath $d -PathType Container)) { continue }
$real = (Get-Item -LiteralPath $d -Force).FullName.TrimEnd('\').ToLowerInvariant()
if ($seen.ContainsKey($real)) { continue }
$seen[$real] = $true
$d
}
}
function Get-ExportNames([string]$kind) { # today's default export file name(s) for the browser
$unpadded = Get-Date -Format 'M_d_yy' # e.g. 11_20_26 (single-digit months/days have no leading zero)
$padded = Get-Date -Format 'MM_dd_yy'
switch ("${Browser}:$kind") {
'chrome:bookmarks' { "bookmarks_$unpadded.html"; "bookmarks_$padded.html" }
'chrome:passwords' { 'Chrome Passwords.csv' }
'edge:bookmarks' { "favorites_$unpadded.html"; "favorites_$padded.html" }
'edge:passwords' { 'Microsoft Edge Passwords.csv' }
'firefox:bookmarks' { 'bookmarks.html' }
'firefox:passwords' { 'logins.csv' }
}
}
function Find-Exports([string]$kind) { # files directly in Documents (no subfolders) saved today
$today = (Get-Date).Date
$script:StaleExports = @()
foreach ($dir in @(Get-ExportFolders)) {
foreach ($fileName in @(Get-ExportNames $kind | Select-Object -Unique)) {
$file = Join-Path $dir $fileName
if (-not (Test-Path -LiteralPath $file -PathType Leaf)) { continue }
$saved = (Get-Item -LiteralPath $file -Force).LastWriteTime
if ($saved.Date -eq $today) {
$file
} else {
$script:StaleExports += "$file (saved $($saved.ToString('yyyy-MM-dd')))"
}
}
}
}
function Get-SizeKB([string[]]$paths) { # total size in KB of the given paths (missing paths count as 0)
[long]$bytes = 0
foreach ($p in $paths) {
if (-not $p -or -not (Test-Path -LiteralPath $p)) { continue }
$item = Get-Item -LiteralPath $p -Force
if ($item.PSIsContainer) {
$sum = (Get-ChildItem -LiteralPath $p -Recurse -Force -File -ErrorAction SilentlyContinue |
Measure-Object -Property Length -Sum).Sum
if ($sum) { $bytes += [long]$sum }
} else {
$bytes += $item.Length
}
}
[long][math]::Floor($bytes / 1024)
}
function Format-Size([long]$kb) { # KB -> readable size
if ($kb -ge 1048576) { return '{0:N2} GB' -f ($kb / 1048576) }
if ($kb -ge 1024) { return '{0:N1} MB' -f ($kb / 1024) }
return "$kb KB"
}
function Start-Browser([string]$key, [string]$address) { # $true if it launched
$exe = Get-ExePath $key
if (-not $exe) { return $false }
try {
if ($address) { Start-Process -FilePath $exe -ArgumentList $address -ErrorAction Stop }
else { Start-Process -FilePath $exe -ErrorAction Stop }
return $true
} catch { return $false }
}
function Show-Links([string]$linksFunction) { # offers the browser pages from a links function as numbered choices
$links = @(& $linksFunction $Browser)
if ($links.Count -eq 0) { return }
Write-Host ''
Write-Host "${BOLD}Open a page in ${BrowserName}:$RESET"
for ($i = 0; $i -lt $links.Count; $i++) {
$parts = $links[$i] -split '\|', 2
Write-Host (' {0}{1}){2} {3,-11} {4}{5}{6}' -f $BOLD, ($i + 1), $RESET, $parts[0], $CYAN, $parts[1], $RESET)
}
while ($true) {
$choice = Read-Host 'Number to open it, or Return to continue'
if ($null -eq $choice) { exit 1 }
if ([string]::IsNullOrWhiteSpace($choice)) { return }
$n = 0
if ([int]::TryParse($choice, [ref]$n) -and $n -ge 1 -and $n -le $links.Count) {
$address = ($links[$n - 1] -split '\|', 2)[1]
if (-not (Start-Browser $Browser $address)) {
Write-Host "${YELLOW}Could not open it - type the address in $BrowserName instead.$RESET"
}
}
}
}
function Stop-Browser([string]$key) { # $true once no process of the browser is left
foreach ($proc in @(Get-BrowserProcesses $key)) {
if ($proc.MainWindowHandle -ne [IntPtr]::Zero) { [void]$proc.CloseMainWindow() }
}
Write-Host -NoNewline "Waiting for $(Get-DisplayName $key) to quit"
$waited = 0
while ($waited -lt $CloseTimeoutSec) {
$left = @(Get-BrowserProcesses $key)
if ($left.Count -eq 0) { Write-Host " ${GREEN}done$RESET"; return $true }
# Closing a window only closes that one window, so keep closing until none are left
if ($waited -lt 10) {
foreach ($proc in $left) { if ($proc.MainWindowHandle -ne [IntPtr]::Zero) { [void]$proc.CloseMainWindow() } }
}
# Only windowless background processes left (Edge startup boost, Chrome background apps):
# no tabs are open, so they are safe to end.
if ($waited -ge 5 -and @($left | Where-Object { $_.MainWindowHandle -ne [IntPtr]::Zero }).Count -eq 0) {
$left | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
if (-not (Test-Running $key)) { Write-Host " ${GREEN}done$RESET"; return $true }
}
Write-Host -NoNewline '.'; Start-Sleep -Seconds 1; $waited++
}
Write-Host ''
Write-Host "$YELLOW$(Get-DisplayName $key) did not quit (it may be showing a `"leave page?`" dialog).$RESET"
if (-not (Confirm-Yes 'Force quit it? Unsaved work in open tabs will be lost')) { return $false }
Get-BrowserProcesses $key | Stop-Process -Force -ErrorAction SilentlyContinue
Start-Sleep -Seconds 2
return (-not (Test-Running $key))
}
# -------------------------------------------------------------------------------------------- steps
function Select-Browser {
Show-Header 'Reset a browser'
$i = 1
foreach ($key in $Browsers) {
if (-not (Test-Installed $key)) { $state = "${DIM}not installed$RESET" }
elseif (-not (Test-HasData $key)) { $state = "${DIM}installed, no profile data yet$RESET" }
elseif (Test-Running $key) { $state = "${GREEN}running$RESET" }
else { $state = 'not running' }
Write-Host (' {0}) {1,-16} {2}' -f $i, (Get-DisplayName $key), $state)
$i++
}
Write-Host ' q) Quit'
Write-Host ''
while ($true) {
$choice = Read-Host 'Which browser are you having issues with?'
if ($null -eq $choice) { exit 1 }
if ($choice -eq 'q') { Stop-Script 'cancelled.' }
$n = 0
if ([int]::TryParse($choice, [ref]$n) -and $n -ge 1 -and $n -le $Browsers.Count) {
$key = $Browsers[$n - 1]
if (-not (Test-Installed $key)) {
Write-Host "$(Get-DisplayName $key) is not installed on this PC. Pick another browser."
} elseif (-not (Test-HasData $key)) {
Write-Host "$(Get-DisplayName $key) has no profile data yet, so there is nothing to reset. Pick another browser."
} else {
$script:Browser = $key; $script:BrowserName = Get-DisplayName $key; return
}
continue
}
Write-Host "Enter a number from 1 to $($Browsers.Count), or q."
}
}
function Invoke-BackupPrompt {
Show-Header "Step 1 of 4: Back up $BrowserName"
if (Test-Running $Browser) {
Write-Host "$GREEN$BrowserName is running$RESET - good, you need it open to export."
} else {
Write-Host "$YELLOW$BrowserName is not running.$RESET Opening it so you can export..."
[void](Start-Browser $Browser)
}
Write-Host ''
Show-BackupSteps $Browser
Write-Host ''
Write-Host "${DIM}Password .csv files are not encrypted - delete them after you re-import.$RESET"
Show-Links 'Get-BackupLinks'
Write-Host ''
if (-not (Confirm-Yes 'Have you exported your bookmarks and passwords?')) {
Stop-Script 'export your bookmarks and passwords first, then run this again.'
}
Test-Exports
}
function Test-Exports {
Show-Header 'Checking your exports'
$missing = @()
Write-Host "Looking in Documents for these files saved today ($(Get-Date -Format 'yyyy-MM-dd')):"
Get-ExportNames 'bookmarks' | Select-Object -Unique | ForEach-Object { Write-Host " $_" }
Get-ExportNames 'passwords' | ForEach-Object { Write-Host " $_" }
Write-Host ''
$bookmarks = @(Find-Exports 'bookmarks'); $stale = @($script:StaleExports)
$passwords = @(Find-Exports 'passwords'); $stale += $script:StaleExports
if ($bookmarks.Count -gt 0) {
Write-Host " ${GREEN}Bookmarks found:$RESET"; $bookmarks | ForEach-Object { Write-Host " $_" }
} else {
$missing += "bookmarks ($(@(Get-ExportNames 'bookmarks')[0]))"
}
if ($passwords.Count -gt 0) {
Write-Host " ${GREEN}Passwords found:$RESET"; $passwords | ForEach-Object { Write-Host " $_" }
} else {
$missing += "passwords ($(@(Get-ExportNames 'passwords')[0]))"
}
if ($missing.Count -gt 0) {
Write-Host ''
Write-Host "${YELLOW}No backup made today was found in Documents for: $($missing -join ', ')$RESET"
if ($stale.Count -gt 0) {
Write-Host 'These older exports were found, but they may be missing recent changes:'
$stale | ForEach-Object { Write-Host " $_" }
}
Write-Host 'Please make fresh backups now using the steps above, saved to Documents, then answer below.'
Show-Links 'Get-BackupLinks'
Write-Host ''
if (-not (Confirm-Yes 'Did you make fresh backups today (in Documents or somewhere else)?')) {
Stop-Script 'make fresh backups of your bookmarks and passwords, then run this again.'
}
}
}
# Earlier backups of this browser: one object per backup set (Suffix, Date, KB).
# A set is every data path with the same ending, e.g. ".bak" or ".bak.20261119-101500".
function Get-EarlierBackups {
$primary = @(Get-DataPaths $Browser)[0]
$parent = Split-Path -Parent $primary
$leaf = Split-Path -Leaf $primary
if (-not (Test-Path -LiteralPath $parent)) { return }
Get-ChildItem -LiteralPath $parent -Force -ErrorAction SilentlyContinue |
Where-Object { $_.Name -eq "$leaf$BakSuffix" -or $_.Name -like "$leaf$BakSuffix.*" } |
Sort-Object Name |
ForEach-Object {
$setSuffix = $_.Name.Substring($leaf.Length)
$kb = 0
foreach ($p in @(Get-DataPaths $Browser)) { $kb += Get-SizeKB "$p$setSuffix" }
[pscustomobject]@{ Suffix = $setSuffix; Date = $_.LastWriteTime.ToString('yyyy-MM-dd HH:mm'); KB = $kb }
}
}
function Move-ToRecycleBin([string]$path) { # moves a path to the Recycle Bin, so it can still be put back
try {
Add-Type -AssemblyName Microsoft.VisualBasic
if (Test-Path -LiteralPath $path -PathType Container) {
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteDirectory($path, 'OnlyErrorDialogs', 'SendToRecycleBin')
} else {
[Microsoft.VisualBasic.FileIO.FileSystem]::DeleteFile($path, 'OnlyErrorDialogs', 'SendToRecycleBin')
}
return (-not (Test-Path -LiteralPath $path))
} catch { return $false }
}
function Invoke-EarlierBackups {
$sets = @(Get-EarlierBackups)
if ($sets.Count -eq 0) { return }
Show-Header "Earlier $BrowserName backups found"
Write-Host "A previous run already backed up ${BrowserName}:"
for ($i = 0; $i -lt $sets.Count; $i++) {
Write-Host (' {0}) {1,-28} {2} {3}({4}){5}' -f ($i + 1), $sets[$i].Suffix, $sets[$i].Date, $DIM, (Format-Size $sets[$i].KB), $RESET)
}
Write-Host @'
What do you want to do?
k) Keep them, and save this reset's backup under a new dated name (recommended)
t) Move them to the Recycle Bin first (they can still be put back from the Recycle Bin)
r) Don't reset - restore one of these earlier backups instead
q) Cancel
'@
while ($true) {
$choice = Read-Host 'Choose k, t, r or q'
if ($null -eq $choice) { exit 1 }
switch ($choice.Trim().ToLowerInvariant()) {
'k' { return }
'q' { Stop-Script 'cancelled.' }
't' {
if (-not (Confirm-Yes "Move $($sets.Count) earlier backup set(s) of $BrowserName to the Recycle Bin?")) { break }
foreach ($set in $sets) {
foreach ($p in @(Get-DataPaths $Browser)) {
$target = "$p$($set.Suffix)"
if (-not (Test-Path -LiteralPath $target)) { continue }
if (Move-ToRecycleBin $target) {
Write-Host " ${GREEN}recycled$RESET $target"
} else {
Write-Host " ${YELLOW}Could not recycle $target - it was left in place.$RESET"
}
}
}
return
}
'r' {
$index = 0
if ($sets.Count -gt 1) {
while ($true) {
$answer = Read-Host "Restore which backup (1-$($sets.Count))?"
if ($null -eq $answer) { exit 1 }
$n = 0
if ([int]::TryParse($answer, [ref]$n) -and $n -ge 1 -and $n -le $sets.Count) { $index = $n - 1; break }
}
}
Restore-EarlierBackup $sets[$index].Suffix
exit 0
}
}
}
}
function Restore-EarlierBackup([string]$setSuffix) { # current profile -> .tmp, backup -> original
Write-Host ''
Write-Host "The current $BrowserName profile will be renamed to '$TmpSuffix' and the"
Write-Host "'$setSuffix' backup put back in its place."
if (-not (Confirm-Yes "Close $BrowserName and restore it now?")) { Stop-Script 'cancelled.' }
if ((Test-Running $Browser) -and -not (Stop-Browser $Browser)) { Stop-Script "$BrowserName is still running." }
Start-Sleep -Seconds 1
foreach ($p in @(Get-DataPaths $Browser)) {
if (-not (Test-Path -LiteralPath "$p$setSuffix")) { continue }
if (Test-Path -LiteralPath $p) {
$tmp = Get-FreeName $p $TmpSuffix
try { Rename-Item -LiteralPath $p -NewName (Split-Path -Leaf $tmp) -ErrorAction Stop }
catch { Write-Host "${RED}Could not rename $p. Stopped here.$RESET"; exit 1 }
Write-Host " ${GREEN}ok$RESET $p"
Write-Host " -> $tmp"
}
try { Rename-Item -LiteralPath "$p$setSuffix" -NewName (Split-Path -Leaf $p) -ErrorAction Stop }
catch { Write-Host "${RED}Could not restore $p$setSuffix. Stopped here.$RESET"; exit 1 }
Write-Host " ${GREEN}ok$RESET $p$setSuffix"
Write-Host " -> $p"
}
Write-Host ''
Write-Host "$GREEN$BrowserName has been restored.$RESET Relaunching..."
[void](Start-Browser $Browser)
}
function Invoke-ImpactPrompt {
Show-Header 'Step 2 of 4: What the reset does'
Write-Host @"
$BrowserName will start fresh.
${BOLD}Can be brought back:$RESET only your ${BOLD}bookmarks and passwords$RESET, by importing the files you exported.
${BOLD}Will be lost:$RESET
- open tabs, tab groups, pinned tabs and "restore last session"
- history, cache and cookies
- website sign-ins: ${BOLD}you'll need to sign back in to each site$RESET
- site permissions (camera, microphone, notifications, pop-ups): sites will ask again
- autofill entries and saved payment methods
- all $BrowserName settings and customizations
"@
if ($Browser -eq 'edge') {
Write-Host ''
Write-Host "${BOLD}Exception:$RESET if you signed in to Edge with a Microsoft account and sync was on,"
Write-Host 'those synced items come back when Edge signs in again.'
}
Write-Host ''
Write-Host 'Nothing is deleted. These will be renamed:'
foreach ($p in @(Get-DataPaths $Browser)) {
if (-not (Test-Path -LiteralPath $p)) { continue }
Write-Host " $p $DIM($(Format-Size (Get-SizeKB $p)))$RESET"
Write-Host " -> $(Get-BackupName $p)"
}
Write-Host " ${BOLD}Total: $(Format-Size $SizeBefore)$RESET"
Write-Host ''
if (-not (Confirm-Yes "OK to close $BrowserName now and back up its data?")) { Stop-Script "cancelled before closing $BrowserName." }
}
function Invoke-Reset {
Show-Header "Step 3 of 4: Close and reset $BrowserName"
if (Test-Running $Browser) {
if (-not (Stop-Browser $Browser)) { Stop-Script "$BrowserName is still running." }
} else {
Write-Host "$BrowserName is not running."
}
Start-Sleep -Seconds 1
$script:Backups = @(); $script:Originals = @()
foreach ($p in @(Get-DataPaths $Browser)) {
if (-not (Test-Path -LiteralPath $p)) { continue }
$dest = Get-BackupName $p
try {
Rename-Item -LiteralPath $p -NewName (Split-Path -Leaf $dest) -ErrorAction Stop
Write-Host " ${GREEN}ok$RESET $p"
Write-Host " -> $dest"
$script:Backups += $dest; $script:Originals += $p
} catch {
Write-Host " ${RED}FAILED$RESET $p"
Write-Host " ${YELLOW}A file in it is in use. Close every $BrowserName window (check the system tray too) and try again.$RESET"
if ($script:Backups.Count -gt 0) {
Write-Host ''
Write-Host "${RED}Partially reset. Already renamed:$RESET"
$script:Backups | ForEach-Object { Write-Host " $_" }
Write-Host "Rename them back (remove the '$BakSuffix' ending) to undo."
}
exit 1
}
}
Write-Host ''
Write-Host "$GREEN$BrowserName has been reset.$RESET"
}
function Invoke-RelaunchAndRestore {
Show-Header 'Step 4 of 4: Restore your bookmarks and passwords'
Write-Host "Relaunching $BrowserName with a fresh profile..."
if (-not (Start-Browser $Browser)) { Write-Host "${YELLOW}Could not open $BrowserName - open it yourself.$RESET" }
Write-Host ''
Show-RestoreSteps $Browser
Write-Host @'
When you're done:
- delete the exported password .csv
- sign back in to websites and re-allow permissions when asked
'@
Show-Links 'Get-RestoreLinks'
}
function Invoke-RevertPrompt {
Show-Header 'Keep the new profile or restore?'
Write-Host " k) Keep the new $BrowserName profile (recommended if the problem is fixed)"
Write-Host " r) Restore my previous $BrowserName browser data"
while ($true) {
$choice = Read-Host 'Choose k or r'
if ($null -eq $choice) { exit 1 }
$choice = $choice.Trim().ToLowerInvariant()
if ($choice -eq 'k') { $script:Reverted = 'no'; return }
if ($choice -eq 'r') { break }
}
Write-Host ''
Write-Host "The new profile will be renamed to '$TmpSuffix' and the '$BakSuffix' backup restored."
Write-Host "Anything you imported since the reset stays in the '$TmpSuffix' folder."
if (-not (Confirm-Yes "Close $BrowserName and restore now?")) { $script:Reverted = 'no'; return }
if ((Test-Running $Browser) -and -not (Stop-Browser $Browser)) {
Write-Host "${YELLOW}Restore cancelled: $BrowserName is still running. Nothing was changed.$RESET"
$script:Reverted = 'no'; return
}
Start-Sleep -Seconds 1
$script:Tmps = @()
for ($i = 0; $i -lt $Backups.Count; $i++) {
$orig = $Originals[$i]; $bak = $Backups[$i]; $tmp = ''
if (Test-Path -LiteralPath $orig) {
$tmp = Get-FreeName $orig $TmpSuffix
try { Rename-Item -LiteralPath $orig -NewName (Split-Path -Leaf $tmp) -ErrorAction Stop }
catch { Invoke-RevertFailed "$orig could not be renamed to $tmp"; return }
Write-Host " ${GREEN}ok$RESET $orig"
Write-Host " -> $tmp"
}
$script:Tmps += $tmp
try { Rename-Item -LiteralPath $bak -NewName (Split-Path -Leaf $orig) -ErrorAction Stop }
catch { Invoke-RevertFailed "$bak could not be renamed back to $orig"; return }
Write-Host " ${GREEN}ok$RESET $bak"
Write-Host " -> $orig"
}
$script:Reverted = 'yes'
Write-Host ''
Write-Host "$GREEN$BrowserName has been restored.$RESET Relaunching..."
[void](Start-Browser $Browser)
}
function Invoke-RevertFailed([string]$reason) {
$script:Reverted = 'failed'
Write-Host ''
Write-Host "${RED}Restore stopped: $reason.$RESET"
Write-Host 'Check the folders listed in the summary and finish the renames by hand.'
}
function Show-Summary {
Show-Header 'Summary'
Write-Host " Browser: $BrowserName"
Write-Host " Before reset: $(Format-Size $SizeBefore)"
if ($Reverted -eq 'yes') {
Write-Host " Rebuilt profile: $(Format-Size (Get-SizeKB $Tmps)) $DIM($TmpSuffix)$RESET"
Write-Host " Current profile: $(Format-Size (Get-SizeKB $Originals)) $DIM(your old data, restored)$RESET"
Write-Host " Outcome: ${YELLOW}Restored browser profile$RESET"
Write-Host " Started: $Started"
Write-Host " Finished: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host ''
Write-Host ' Folders renamed:'
for ($i = 0; $i -lt $Backups.Count; $i++) {
if ($i -lt $Tmps.Count -and $Tmps[$i]) {
Write-Host " $($Originals[$i]) (new)"
Write-Host " -> $($Tmps[$i])"
}
Write-Host " $($Backups[$i])"
Write-Host " -> $($Originals[$i]) (restored)"
}
Write-Host ''
Write-Host "${GREEN}All done.$RESET"
return
}
$after = Get-SizeKB $Originals
Write-Host " After rebuild: $(Format-Size $after) $DIM(new profile, measured now)$RESET"
Write-Host " Kept as backup: $(Format-Size (Get-SizeKB $Backups))"
if ($Reverted -eq 'failed') { Write-Host " Outcome: ${RED}Restore did not finish - see above$RESET" }
Write-Host " Started: $Started"
Write-Host " Finished: $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')"
Write-Host ''
Write-Host ' Folders renamed:'
for ($i = 0; $i -lt $Backups.Count; $i++) {
Write-Host " $($Originals[$i])"
Write-Host " -> $($Backups[$i])"
}
Write-Host ''
Write-Host " ${BOLD}Need your old profile back?$RESET Run this script again, choose $BrowserName, then choose (r) to restore the backup."
Write-Host ''
Write-Host "${GREEN}All done.$RESET"
}
# --------------------------------------------------------------------------------------------- main
if ($env:OS -ne 'Windows_NT') { Write-Host 'This script is for Windows only.'; exit 1 }
$principal = New-Object Security.Principal.WindowsPrincipal([Security.Principal.WindowsIdentity]::GetCurrent())
if ($principal.IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)) {
Write-Host 'Run this as yourself, not as administrator.'; exit 1
}
$Started = Get-Date -Format 'yyyy-MM-dd HH:mm:ss'
Select-Browser
$SizeBefore = Get-SizeKB @(Get-DataPaths $Browser)
Invoke-EarlierBackups
Invoke-BackupPrompt
Invoke-ImpactPrompt
Invoke-Reset
Invoke-RelaunchAndRestore
$Reverted = 'no'
Invoke-RevertPrompt
Show-Summary
macOS (Bash)
#!/bin/bash
#
# ResetBrowserLocal.sh - interactive browser reset for this Mac.
#
# Walks you through: pick a browser > back up bookmarks and passwords > close the browser >
# check the exports are in Documents > rename its data folder(s) to '.bak' > relaunch it >
# restore your bookmarks and passwords > optionally revert to the old profile > summary.
# Nothing is deleted. Reverting renames the new profile to '.tmp' and the '.bak' back.
#
# Usage: bash ResetBrowserLocal.sh (from Terminal, in the folder you saved it to)
set -u
BOLD=$'\033[1m'; DIM=$'\033[2m'; RED=$'\033[31m'; GREEN=$'\033[32m'; YELLOW=$'\033[33m'; CYAN=$'\033[36m'; RESET=$'\033[0m'
SUFFIX=".bak"
TMP_SUFFIX=".tmp"
CLOSE_TIMEOUT_SEC=20
BROWSERS="edge chrome firefox safari"
# ───────────────────────────────────────────────────────────────────────────────────── browser info
display_name() {
case "$1" in
edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
firefox) echo "Mozilla Firefox" ;; safari) echo "Safari" ;;
esac
}
app_name() { # name used by 'open -a' and AppleScript
case "$1" in
edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
firefox) echo "Firefox" ;; safari) echo "Safari" ;;
esac
}
process_name() {
case "$1" in
edge) echo "Microsoft Edge" ;; chrome) echo "Google Chrome" ;;
firefox) echo "firefox" ;; safari) echo "Safari" ;;
esac
}
data_paths() { # profile folder first, then caches
case "$1" in
edge)
echo "$HOME/Library/Application Support/Microsoft Edge"
echo "$HOME/Library/Caches/Microsoft Edge" ;;
chrome)
echo "$HOME/Library/Application Support/Google/Chrome"
echo "$HOME/Library/Caches/Google/Chrome" ;;
firefox)
echo "$HOME/Library/Application Support/Firefox"
echo "$HOME/Library/Caches/Firefox" ;;
safari)
echo "$HOME/Library/Safari"
echo "$HOME/Library/Containers/com.apple.Safari"
echo "$HOME/Library/Caches/com.apple.Safari"
echo "$HOME/Library/Preferences/com.apple.Safari.plist" ;;
esac
}
# Browser pages used in the steps: "label|address". They are opened with 'open -a <browser>',
# because macOS has no handler for chrome://, edge:// or about: addresses when clicked in Terminal.
backup_links() {
case "$1" in
edge) echo "Favorites|edge://favorites"; echo "Passwords|edge://settings/autofill/passwords" ;;
chrome) echo "Bookmarks|chrome://bookmarks"; echo "Passwords|chrome://password-manager/settings" ;;
firefox) echo "Passwords|about:logins" ;;
esac
}
restore_links() {
case "$1" in
edge) echo "Favorites|edge://favorites"; echo "Passwords|edge://settings/autofill/passwords" ;;
chrome) echo "Bookmarks|chrome://bookmarks"; echo "Passwords|chrome://password-manager/settings" ;;
firefox) echo "Passwords|about:logins" ;;
esac
}
is_installed() { open -Ra "$(app_name "$1")" >/dev/null 2>&1; }
is_running() { pgrep -x -U "$(id -u)" "$(process_name "$1")" >/dev/null 2>&1; }
has_data() { [[ -e "$(data_paths "$1" | head -n 1)" ]]; }
backup_steps() {
case "$1" in
edge) cat <<'EOF'
Favorites: open edge://favorites > More options (...) > Export favorites
Save the .html file to Documents.
Passwords: open edge://settings/autofill/passwords > (...) > Export passwords
Save the .csv file to Documents.
EOF
;;
chrome) cat <<'EOF'
Bookmarks: open chrome://bookmarks > three dots (top right) > Export bookmarks
Save the .html file to Documents.
Passwords: open chrome://password-manager/settings > Export passwords > Download file
Save the .csv file to Documents.
EOF
;;
firefox) cat <<'EOF'
Bookmarks: Cmd+Shift+O > Import and Backup > Export Bookmarks to HTML
Save the .html file to Documents.
Passwords: open about:logins > three dots (...) > Export Passwords
Save the .csv file to Documents.
EOF
;;
safari) cat <<'EOF'
Bookmarks: File > Export > Bookmarks. Save the .html file to Documents.
Passwords: Safari passwords live in the Passwords app / Keychain and are NOT touched
by this reset. To keep a copy anyway: Passwords app > File > Export All Passwords.
Note: Reading List and history can't be exported and will be lost.
EOF
;;
esac
}
restore_steps() {
case "$1" in
edge) cat <<'EOF'
1. Favorites: open edge://favorites > More options (...) > Import favorites
> "Favorites or bookmarks HTML file" > choose your .html file.
2. Passwords: open edge://settings/autofill/passwords > (...) > Import passwords
> choose your .csv file.
EOF
;;
chrome) cat <<'EOF'
1. Bookmarks: open chrome://bookmarks > three dots (top right) > Import bookmarks
> choose your .html file (they appear in an "Imported" folder).
2. Passwords: open chrome://password-manager/settings > Import passwords > Select file
> choose your .csv file.
EOF
;;
firefox) cat <<'EOF'
1. Bookmarks: Cmd+Shift+O > Import and Backup > Import Bookmarks from HTML
> choose your .html file.
2. Passwords: open about:logins > three dots (...) > Import from a File > choose your .csv file.
EOF
;;
safari) cat <<'EOF'
1. Bookmarks: File > Import From > Bookmarks HTML File > choose your .html file.
2. Passwords: nothing to do - they are still in the Passwords app / Keychain.
EOF
;;
esac
}
# ────────────────────────────────────────────────────────────────────────────────────────── helpers
header() { printf '\n%s== %s ==%s\n\n' "$BOLD$CYAN" "$1" "$RESET"; }
confirm() { # confirm "question" -> 0 for yes
local answer
while true; do
read -r -p "$1 [y/n]: " answer || exit 1
case "$(printf '%s' "$answer" | tr '[:upper:]' '[:lower:]')" in
y|yes) return 0 ;;
n|no) return 1 ;;
esac
done
}
abort() { printf '\n%sStopped: %s%s\nNothing was changed.\n' "$YELLOW" "$1" "$RESET"; exit 0; }
free_name() { # free_name <path> <suffix>: never overwrites an existing folder
if [[ ! -e "$1$2" ]]; then echo "$1$2"; else echo "$1$2.$(date '+%Y%m%d-%H%M%S')"; fi
}
backup_name() { free_name "$1" "$SUFFIX"; }
export_folders() { # Documents, plus OneDrive's Documents if it is a different folder
local d real seen=""
for d in "$HOME/Documents" "$HOME"/Library/CloudStorage/OneDrive*/Documents; do
[[ -d "$d" ]] || continue
real=$(cd -P "$d" 2>/dev/null && pwd)
[[ "$seen" == *"|$real|"* ]] && continue
seen="$seen|$real|"
echo "$d"
done
}
export_names() { # export_names <bookmarks|passwords>: today's default export file name(s) for the browser
local unpadded padded
unpadded="$(date '+%-m_%-d_%y')" # e.g. 11_20_26 (single-digit months/days have no leading zero)
padded="$(date '+%m_%d_%y')"
case "$BROWSER:$1" in
chrome:bookmarks) echo "bookmarks_$unpadded.html"; echo "bookmarks_$padded.html" ;;
chrome:passwords) echo "Chrome Passwords.csv" ;;
edge:bookmarks) echo "favorites_$unpadded.html"; echo "favorites_$padded.html" ;;
edge:passwords) echo "Microsoft Edge Passwords.csv" ;;
firefox:bookmarks) echo "bookmarks.html" ;;
firefox:passwords) echo "logins.csv" ;;
safari:bookmarks) echo "Safari Bookmarks.html" ;;
esac
}
file_date() { stat -f '%Sm' -t '%Y-%m-%d' "$1" 2>/dev/null; } # last saved, local time
find_exports() { # find_exports <bookmarks|passwords>: files directly in Documents (no subfolders) saved today
local dir name today
today=$(date '+%Y-%m-%d')
STALE_EXPORTS=""
while IFS= read -r dir; do
while IFS= read -r name; do
[[ -n "$name" && -f "$dir/$name" ]] || continue
if [[ "$(file_date "$dir/$name")" == "$today" ]]; then
echo "$dir/$name"
else
STALE_EXPORTS="$STALE_EXPORTS$dir/$name (saved $(file_date "$dir/$name"))"$'\n'
fi
done <<< "$(export_names "$1" | sort -u)"
done <<< "$(export_folders)"
}
size_kb() { # total size in KB of the given paths (missing paths count as 0)
local total=0 p kb
for p in "$@"; do
[[ -e "$p" ]] || continue
kb=$(du -sk "$p" 2>/dev/null | awk '{print $1}')
total=$((total + ${kb:-0}))
done
echo "$total"
}
human() { # KB -> readable size
awk -v k="$1" 'BEGIN { if (k >= 1048576) printf "%.2f GB", k/1048576;
else if (k >= 1024) printf "%.1f MB", k/1024; else printf "%d KB", k }'
}
open_links() { # offers the browser pages from a links function as numbered choices
local func="$1" lines=() line i choice
while IFS= read -r line; do [[ -n "$line" ]] && lines+=("$line"); done <<< "$("$func" "$BROWSER")"
[[ ${#lines[@]} -eq 0 ]] && return
echo
echo "${BOLD}Open a page in $NAME:${RESET}"
for i in "${!lines[@]}"; do
printf ' %s%d)%s %-11s %s%s%s\n' "$BOLD" $((i + 1)) "$RESET" "${lines[$i]%%|*}" "$CYAN" "${lines[$i]#*|}" "$RESET"
done
while true; do
read -r -p "Number to open it, or Return to continue: " choice || exit 1
[[ -z "$choice" ]] && return
if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#lines[@]} )); then
open -a "$(app_name "$BROWSER")" "${lines[$((choice - 1))]#*|}" 2>/dev/null \
|| printf '%sCould not open it - type the address in %s instead.%s\n' "$YELLOW" "$NAME" "$RESET"
fi
done
}
quit_browser() {
local key="$1" waited=0
osascript -e "tell application \"$(app_name "$key")\" to quit" >/dev/null 2>&1
printf 'Waiting for %s to quit' "$(display_name "$key")"
while (( waited < CLOSE_TIMEOUT_SEC )); do
is_running "$key" || { printf ' %sdone%s\n' "$GREEN" "$RESET"; return 0; }
printf '.'; sleep 1; waited=$((waited + 1))
done
printf '\n%s%s did not quit (it may be showing a "leave page?" dialog).%s\n' "$YELLOW" "$(display_name "$key")" "$RESET"
confirm "Force quit it? Unsaved work in open tabs will be lost" || return 1
pkill -x -U "$(id -u)" "$(process_name "$key")"; sleep 2
is_running "$key" && { pkill -9 -x -U "$(id -u)" "$(process_name "$key")"; sleep 2; }
! is_running "$key"
}
# ──────────────────────────────────────────────────────────────────────────────────────────── steps
choose_browser() {
header "Reset a browser"
local keys=() key i=1 state choice
for key in $BROWSERS; do
if ! is_installed "$key"; then
state="${DIM}not installed${RESET}"
elif ! has_data "$key"; then
state="${DIM}installed, no profile data yet${RESET}"
elif is_running "$key"; then
state="${GREEN}running${RESET}"
else
state="not running"
fi
printf ' %d) %-16s %s\n' "$i" "$(display_name "$key")" "$state"
keys+=("$key"); i=$((i + 1))
done
printf ' q) Quit\n\n'
while true; do
read -r -p "Which browser are you having issues with? " choice || exit 1
[[ "$choice" == [qQ] ]] && abort "cancelled."
if [[ "$choice" =~ ^[0-9]+$ ]] && (( choice >= 1 && choice <= ${#keys[@]} )); then
key="${keys[$((choice - 1))]}"
if ! is_installed "$key"; then
echo "$(display_name "$key") is not installed on this Mac. Pick another browser."
elif ! has_data "$key"; then
echo "$(display_name "$key") has no profile data yet, so there is nothing to reset. Pick another browser."
else
BROWSER="$key"; NAME=$(display_name "$key"); return
fi
continue
fi
echo "Enter a number from 1 to ${#keys[@]}, or q."
done
}
backup_prompt() {
header "Step 1 of 4: Back up $NAME"
if is_running "$BROWSER"; then
printf '%s%s is running%s - good, you need it open to export.\n\n' "$GREEN" "$NAME" "$RESET"
else
printf '%s%s is not running.%s Opening it so you can export...\n\n' "$YELLOW" "$NAME" "$RESET"
open -a "$(app_name "$BROWSER")" 2>/dev/null
fi
backup_steps "$BROWSER"
printf '\n%sPassword .csv files are not encrypted - delete them after you re-import.%s\n' "$DIM" "$RESET"
open_links backup_links
echo
confirm "Have you exported your bookmarks and passwords?" \
|| abort "export your bookmarks and passwords first, then run this again."
check_exports
}
check_exports() {
header "Checking your exports"
local bookmarks passwords missing=()
echo "Looking in Documents for these files saved today ($(date '+%Y-%m-%d')):"
export_names bookmarks | sort -u | sed 's/^/ /'
[[ "$BROWSER" != "safari" ]] && export_names passwords | sed 's/^/ /'
echo
local stale=""
find_exports bookmarks > /tmp/.rbl_$$; bookmarks=$(cat /tmp/.rbl_$$); stale="$STALE_EXPORTS"
if [[ "$BROWSER" != "safari" ]]; then
find_exports passwords > /tmp/.rbl_$$; passwords=$(cat /tmp/.rbl_$$); stale="$stale$STALE_EXPORTS"
fi
rm -f /tmp/.rbl_$$
if [[ -n "$bookmarks" ]]; then
printf ' %sBookmarks found:%s\n' "$GREEN" "$RESET"; printf '%s\n' "$bookmarks" | sed 's/^/ /'
else
missing+=("bookmarks ($(export_names bookmarks | head -n 1))")
fi
if [[ "$BROWSER" == "safari" ]]; then
echo " Passwords: not needed for Safari (they stay in the Passwords app)."
elif [[ -n "$passwords" ]]; then
printf ' %sPasswords found:%s\n' "$GREEN" "$RESET"; printf '%s\n' "$passwords" | sed 's/^/ /'
else
missing+=("passwords ($(export_names passwords | head -n 1))")
fi
if (( ${#missing[@]} > 0 )); then
printf '\n%sNo backup made today was found in Documents for: %s%s\n' "$YELLOW" "$(IFS=,; echo "${missing[*]}" | sed 's/,/, /g')" "$RESET"
if [[ -n "$stale" ]]; then
echo "These older exports were found, but they may be missing recent changes:"
printf '%s' "$stale" | sed 's/^/ /'
fi
echo "Please make fresh backups now using the steps above, saved to Documents, then answer below."
open_links backup_links
echo
confirm "Did you make fresh backups today (in Documents or somewhere else)?" \
|| abort "make fresh backups of your bookmarks and passwords, then run this again."
fi
}
# Earlier backups of this browser: one line per backup set, as "<suffix>|<date>|<size KB>".
# A set is every data path with the same ending, e.g. ".bak" or ".bak.20261119-101500".
earlier_backups() {
local primary suffix b paths p kb
primary=$(data_paths "$BROWSER" | head -n 1)
for b in "$primary$SUFFIX" "$primary$SUFFIX".*; do
[[ -e "$b" ]] || continue
suffix="${b#"$primary"}"
kb=0
while IFS= read -r p; do kb=$((kb + $(size_kb "$p$suffix"))); done <<< "$(data_paths "$BROWSER")"
printf '%s|%s|%s\n' "$suffix" "$(stat -f '%Sm' -t '%Y-%m-%d %H:%M' "$b")" "$kb"
done
}
trash() { # moves a path to the Trash through Finder, so it can still be put back
osascript -e "tell application \"Finder\" to delete (POSIX file \"$1\" as alias)" >/dev/null 2>&1
}
handle_earlier_backups() {
local sets=() line i choice suffix p
while IFS= read -r line; do [[ -n "$line" ]] && sets+=("$line"); done <<< "$(earlier_backups)"
(( ${#sets[@]} == 0 )) && return
header "Earlier $NAME backups found"
echo "A previous run already backed up $NAME:"
for i in "${!sets[@]}"; do
IFS='|' read -r suffix line p <<< "${sets[$i]}"
printf ' %d) %-28s %s %s(%s)%s\n' $((i + 1)) "${suffix}" "$line" "$DIM" "$(human "$p")" "$RESET"
done
cat <<EOF
What do you want to do?
k) Keep them, and save this reset's backup under a new dated name (recommended)
t) Move them to the Trash first (they can still be put back from the Trash)
r) Don't reset - restore one of these earlier backups instead
q) Cancel
EOF
while true; do
read -r -p "Choose k, t, r or q: " choice || exit 1
case "$choice" in
[kK]) return ;;
[qQ]) abort "cancelled." ;;
[tT])
confirm "Move ${#sets[@]} earlier backup set(s) of $NAME to the Trash?" || continue
for i in "${!sets[@]}"; do
suffix="${sets[$i]%%|*}"
while IFS= read -r p; do
[[ -e "$p$suffix" ]] || continue
if trash "$p$suffix"; then
printf ' %strashed%s %s\n' "$GREEN" "$RESET" "$p$suffix"
else
printf ' %sCould not trash %s - it was left in place.%s\n' "$YELLOW" "$p$suffix" "$RESET"
fi
done <<< "$(data_paths "$BROWSER")"
done
return ;;
[rR])
if (( ${#sets[@]} == 1 )); then i=0; else
while true; do
read -r -p "Restore which backup (1-${#sets[@]})? " i || exit 1
[[ "$i" =~ ^[0-9]+$ ]] && (( i >= 1 && i <= ${#sets[@]} )) && { i=$((i - 1)); break; }
done
fi
restore_earlier "${sets[$i]%%|*}"
exit 0 ;;
esac
done
}
restore_earlier() { # restore_earlier <suffix>: current profile -> .tmp, backup -> original
local suffix="$1" p tmp
echo
echo "The current $NAME profile will be renamed to '$TMP_SUFFIX' and the"
echo "'$suffix' backup put back in its place."
confirm "Close $NAME and restore it now?" || abort "cancelled."
if is_running "$BROWSER"; then quit_browser "$BROWSER" || abort "$NAME is still running."; fi
sleep 1
while IFS= read -r p; do
[[ -e "$p$suffix" ]] || continue
if [[ -e "$p" ]]; then
tmp=$(free_name "$p" "$TMP_SUFFIX")
mv "$p" "$tmp" 2>/dev/null || { printf '%sCould not rename %s. Stopped here.%s\n' "$RED" "$p" "$RESET"; exit 1; }
printf ' %sok%s %s\n -> %s\n' "$GREEN" "$RESET" "$p" "$tmp"
fi
mv "$p$suffix" "$p" 2>/dev/null || { printf '%sCould not restore %s. Stopped here.%s\n' "$RED" "$p$suffix" "$RESET"; exit 1; }
printf ' %sok%s %s\n -> %s\n' "$GREEN" "$RESET" "$p$suffix" "$p"
done <<< "$(data_paths "$BROWSER")"
[[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
printf '\n%s%s has been restored.%s Relaunching...\n' "$GREEN" "$NAME" "$RESET"
open -a "$(app_name "$BROWSER")" 2>/dev/null
}
impact_prompt() {
header "Step 2 of 4: What the reset does"
cat <<EOF
$NAME will start fresh.
${BOLD}Can be brought back:${RESET} only your ${BOLD}bookmarks and passwords${RESET}, by importing the files you exported.
${BOLD}Will be lost:${RESET}
- open tabs, tab groups, pinned tabs and "restore last session"
- history, cache and cookies
- website sign-ins: ${BOLD}you'll need to sign back in to each site${RESET}
- site permissions (camera, microphone, notifications, pop-ups): sites will ask again
- autofill entries and saved payment methods
- all $NAME settings and customizations
EOF
if [[ "$BROWSER" == "edge" ]]; then
printf '\n%sException:%s if you signed in to Edge with a Microsoft account and sync was on,\nthose synced items come back when Edge signs in again.\n' "$BOLD" "$RESET"
fi
cat <<EOF
Nothing is deleted. These will be renamed:
EOF
local p
while IFS= read -r p; do
[[ -e "$p" ]] && printf ' %s %s(%s)%s\n -> %s\n' "$p" "$DIM" "$(human "$(size_kb "$p")")" "$RESET" "$(backup_name "$p")"
done <<< "$(data_paths "$BROWSER")"
printf ' %sTotal: %s%s\n\n' "$BOLD" "$(human "$SIZE_BEFORE")" "$RESET"
confirm "OK to close $NAME now and back up its data?" || abort "cancelled before closing $NAME."
}
do_reset() {
header "Step 3 of 4: Close and reset $NAME"
if is_running "$BROWSER"; then
quit_browser "$BROWSER" || abort "$NAME is still running."
else
echo "$NAME is not running."
fi
sleep 1
local p dest moved=0
BACKUPS=(); ORIGINALS=()
while IFS= read -r p; do
[[ -e "$p" ]] || continue
dest=$(backup_name "$p")
if mv "$p" "$dest" 2>/dev/null; then
printf ' %sok%s %s\n -> %s\n' "$GREEN" "$RESET" "$p" "$dest"
BACKUPS+=("$dest"); ORIGINALS+=("$p"); moved=$((moved + 1))
else
printf ' %sFAILED%s %s\n' "$RED" "$RESET" "$p"
[[ "$BROWSER" == "safari" ]] && printf ' %sGive Terminal Full Disk Access (System Settings > Privacy & Security) and try again.%s\n' "$YELLOW" "$RESET"
if (( moved > 0 )); then
printf '\n%sPartially reset. Already renamed:%s\n' "$RED" "$RESET"; printf ' %s\n' "${BACKUPS[@]}"
echo "Rename them back (remove the '$SUFFIX' ending) to undo."
fi
exit 1
fi
done <<< "$(data_paths "$BROWSER")"
# Safari prefs are cached by cfprefsd, which would write the old values back
[[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
printf '\n%s%s has been reset.%s\n' "$GREEN" "$NAME" "$RESET"
}
relaunch_and_restore() {
header "Step 4 of 4: Restore your bookmarks and passwords"
echo "Relaunching $NAME with a fresh profile..."
open -a "$(app_name "$BROWSER")" 2>/dev/null || printf '%sCould not open %s - open it yourself.%s\n' "$YELLOW" "$NAME" "$RESET"
echo
restore_steps "$BROWSER"
cat <<EOF
When you're done:
- delete the exported password .csv
- sign back in to websites and re-allow permissions when asked
EOF
open_links restore_links
}
revert_prompt() {
header "Keep the new profile or restore?"
echo " k) Keep the new $NAME profile (recommended if the problem is fixed)"
echo " r) Restore my previous $NAME browser data"
local choice
while true; do
read -r -p "Choose k or r: " choice || exit 1
case "$choice" in
[kK]) REVERTED=no; return ;;
[rR]) break ;;
esac
done
echo
echo "The new profile will be renamed to '$TMP_SUFFIX' and the '$SUFFIX' backup restored."
echo "Anything you imported since the reset stays in the '$TMP_SUFFIX' folder."
confirm "Close $NAME and restore now?" || { REVERTED=no; return; }
if is_running "$BROWSER"; then
quit_browser "$BROWSER" || { printf '%sRestore cancelled: %s is still running. Nothing was changed.%s\n' "$YELLOW" "$NAME" "$RESET"; REVERTED=no; return; }
fi
sleep 1
local i orig bak tmp
TMPS=()
for i in "${!BACKUPS[@]}"; do
orig="${ORIGINALS[$i]}"; bak="${BACKUPS[$i]}"; tmp=""
if [[ -e "$orig" ]]; then
tmp=$(free_name "$orig" "$TMP_SUFFIX")
mv "$orig" "$tmp" 2>/dev/null || { revert_failed "$orig could not be renamed to $tmp"; return; }
printf ' %sok%s %s\n -> %s\n' "$GREEN" "$RESET" "$orig" "$tmp"
fi
TMPS+=("$tmp")
mv "$bak" "$orig" 2>/dev/null || { revert_failed "$bak could not be renamed back to $orig"; return; }
printf ' %sok%s %s\n -> %s\n' "$GREEN" "$RESET" "$bak" "$orig"
done
[[ "$BROWSER" == "safari" ]] && killall -u "$(id -un)" cfprefsd >/dev/null 2>&1
REVERTED=yes
printf '\n%s%s has been restored.%s Relaunching...\n' "$GREEN" "$NAME" "$RESET"
open -a "$(app_name "$BROWSER")" 2>/dev/null
}
revert_failed() {
REVERTED=failed
printf '\n%sRestore stopped: %s.%s\n' "$RED" "$1" "$RESET"
echo "Check the folders listed in the summary and finish the renames by hand."
}
summary() {
local p after=0 i
header "Summary"
printf ' Browser: %s\n' "$NAME"
printf ' Before reset: %s\n' "$(human "$SIZE_BEFORE")"
if [[ "$REVERTED" == "yes" ]]; then
printf ' Rebuilt profile: %s %s(%s)%s\n' "$(human "$(size_kb "${TMPS[@]}")")" "$DIM" "$TMP_SUFFIX" "$RESET"
printf ' Current profile: %s %s(your old data, restored)%s\n' "$(human "$(size_kb "${ORIGINALS[@]}")")" "$DIM" "$RESET"
printf ' Outcome: %sRestored browser profile%s\n' "$YELLOW" "$RESET"
printf ' Started: %s\n Finished: %s\n\n' "$STARTED" "$(date '+%Y-%m-%d %H:%M:%S')"
echo " Folders renamed:"
for i in "${!BACKUPS[@]}"; do
[[ -n "${TMPS[$i]}" ]] && printf ' %s (new)\n -> %s\n' "${ORIGINALS[$i]}" "${TMPS[$i]}"
printf ' %s\n -> %s (restored)\n' "${BACKUPS[$i]}" "${ORIGINALS[$i]}"
done
printf '\n%sAll done.%s\n' "$GREEN" "$RESET"
return
fi
for p in "${ORIGINALS[@]}"; do after=$((after + $(size_kb "$p"))); done
printf ' After rebuild: %s %s(new profile, measured now)%s\n' "$(human "$after")" "$DIM" "$RESET"
printf ' Kept as backup: %s\n' "$(human "$(size_kb "${BACKUPS[@]}")")"
[[ "$REVERTED" == "failed" ]] && printf ' Outcome: %sRestore did not finish - see above%s\n' "$RED" "$RESET"
printf ' Started: %s\n Finished: %s\n\n' "$STARTED" "$(date '+%Y-%m-%d %H:%M:%S')"
echo " Folders renamed:"
for i in "${!BACKUPS[@]}"; do
printf ' %s\n -> %s\n' "${ORIGINALS[$i]}" "${BACKUPS[$i]}"
done
printf '\n %sNeed your old profile back?%s Run this script again, choose %s, then choose (r) to restore the backup.\n' "$BOLD" "$RESET" "$NAME"
printf '\n%sAll done.%s\n' "$GREEN" "$RESET"
}
# ───────────────────────────────────────────────────────────────────────────────────────────── main
[[ "$(uname)" == "Darwin" ]] || { echo "This script is for macOS only."; exit 1; }
[[ $EUID -eq 0 ]] && { echo "Run this as yourself, not with sudo."; exit 1; }
STARTED=$(date '+%Y-%m-%d %H:%M:%S')
choose_browser
PATHS=(); while IFS= read -r p; do PATHS+=("$p"); done <<< "$(data_paths "$BROWSER")"
SIZE_BEFORE=$(size_kb "${PATHS[@]}")
handle_earlier_backups
backup_prompt
impact_prompt
do_reset
relaunch_and_restore
REVERTED=no
revert_prompt
summary
Lessons Learned
Browser pages can't be opened like links: Windows and macOS have no handler for chrome://, edge:// or about: addresses, so opening one the normal way does nothing. Passing the address straight to the browser's own executable (open -a on the Mac) works.
Finding the browser on Windows: Chrome can be installed per-user under %LOCALAPPDATA% or system-wide under Program Files. The registry's App Paths keys are the reliable place to look, with the usual install folders as a fallback.
Export file names aren't consistent: Chrome and Edge name bookmark exports after the date, and depending on the version, single-digit months and days may or may not have a leading zero. The check looks for both bookmarks_1_5_26.html and bookmarks_01_05_26.html.
Safari's preferences come back from the dead: macOS caches preferences in cfprefsd, which will happily write the old Safari settings back after the plist is renamed. Restarting cfprefsd for the current user after each rename fixes that.
Documents isn't always Documents: with OneDrive folder backup turned on, Windows redirects Documents into OneDrive. Asking Windows for the real Documents path, rather than assuming %USERPROFILE%\Documents, means the export check looks in the right place.
Feel free to use them, change them, and send feedback. I'm always looking for ways to improve my work.