Skip to content

Instantly share code, notes, and snippets.

@ekinertac
Last active November 4, 2024 12:29
Show Gist options
  • Save ekinertac/6b739675de10c4e492d5cb3721dee4a1 to your computer and use it in GitHub Desktop.
Save ekinertac/6b739675de10c4e492d5cb3721dee4a1 to your computer and use it in GitHub Desktop.
Copy to clipboard the latest OTP from macOS Messages
#!/bin/bash
# Path to original iMessage database
DB_PATH="$HOME/Library/Messages/chat.db"
# Create a safe copy to avoid locking the original database
TEMP_DB_PATH="$HOME/Documents/imessage-chat.db"
# Check if original database exists
if [ ! -f "$DB_PATH" ]; then
echo "Error: iMessage database not found at $DB_PATH"
exit 1
fi
# Create safe copy of database
cp "$DB_PATH" "$TEMP_DB_PATH"
# Use the safe copy for queries
DB_PATH="$TEMP_DB_PATH"
# Query to fetch the latest messages
OTP_MESSAGE=$(sqlite3 "$DB_PATH" "SELECT text FROM message ORDER BY date DESC LIMIT 1;" 2>/dev/null)
# Check if sqlite3 command failed
if [ $? -ne 0 ]; then
echo "Error: Permission denied when accessing iMessage database"
echo "Please follow these steps to grant access:"
echo " 1. Open System Settings"
echo " 2. Go to Privacy & Security > Full Disk Access"
echo " 3. Click the '+' button"
echo " 4. Find and select your terminal application (Terminal.app, iTerm, etc.)"
echo " 5. Restart your terminal application"
echo " 6. Try running this script again"
rm "$TEMP_DB_PATH" 2>/dev/null
exit 1
fi
# Check if we found messages
if [ -n "$OTP_MESSAGE" ]; then
# Extract 4, 5, or 6 digit numbers from the messages
# Using negative lookbehind (?<![A-Za-z]) to ensure no letters before the number
OTP=$(echo "$OTP_MESSAGE" | grep -o '[^A-Za-z][0-9]\{4,6\}\b' | sed 's/^[^0-9]*//' | head -n 1)
# Copy OTP to clipboard if found
if [ -n "$OTP" ]; then
echo "$OTP" | pbcopy
echo "OTP copied to clipboard: $OTP"
echo "Message: $OTP_MESSAGE"
else
echo "Failed to extract OTP from message."
fi
else
echo "No recent messages found."
fi
# Cleanup temporary database
rm "$TEMP_DB_PATH" 2>/dev/null
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment