Skip to content

Instantly share code, notes, and snippets.

@jfinstrom
Created June 6, 2024 21:49
Show Gist options
  • Save jfinstrom/53519253b686b985e714fd03abd36de3 to your computer and use it in GitHub Desktop.
Save jfinstrom/53519253b686b985e714fd03abd36de3 to your computer and use it in GitHub Desktop.
Fix a corrupt sqlite database.
#!/bin/bash
# Check if a database file is provided
if [ -z "$1" ]; then
echo "Usage: $0 your_database_file.db"
exit 1
fi
DB_FILE=$1
DUMP_FILE="dump.sql"
NEW_DB_FILE="new_$DB_FILE"
# Check the integrity of the database
integrity=$(sqlite3 $DB_FILE "PRAGMA integrity_check;")
if [ "$integrity" == "ok" ]; then
echo "Database is not corrupt."
exit 0
else
echo "Database is corrupt. Attempting to recover..."
fi
# Dump the database contents
sqlite3 $DB_FILE ".dump" > $DUMP_FILE
# Check if the dump file was created
if [ ! -f "$DUMP_FILE" ]; then
echo "Failed to create dump file."
exit 1
fi
# Create a new database and import the dump
sqlite3 $NEW_DB_FILE < $DUMP_FILE
# Check the integrity of the new database
new_integrity=$(sqlite3 $NEW_DB_FILE "PRAGMA integrity_check;")
if [ "$new_integrity" == "ok" ]; then
echo "Recovery successful. New database file: $NEW_DB_FILE"
# Clean up the dump file
rm $DUMP_FILE
exit 0
else
echo "Recovery failed. New database is also corrupt."
exit 1
fi
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment