Submit Hint Search The Forums LinksStatsPollsHeadlinesRSS
14,000 hints and counting!


Click here to return to the 'Create a Time Machine-like feature for Safari tabs' hint
The following comments are owned by whoever posted them. This site is not responsible for what they say.
Create a Time Machine-like feature for Safari tabs
Authored by: emailboy on Jan 28, '11 04:57:55PM
I found I was getting way too many saved files (as in, thousands and thousands), plus I was still getting launchd errors. I modified the script to keep all of today's files, but only the oldest file from each previous day:

#!/bin/bash

#
# Script to create backup copy of Safari's "Last Session" state, to
# protect against accidently quitting Safari without clicking
# "Reopen all windows from last session".
#
# Script is run by LaunchAgent in ~/Library/LaunchAgents directory
# with LastSession.plist as watchfile.
#

#
# Echo a line to denote start of execution
# (makes it easier when looking in the log)
#
echo "---------- $(date) ----------"

#
# Create "LastSessionTimeMachine" directory if it doesn't exist
#
mkdir -p ~/Library/Safari/LastSessionTimeMachine

#
# Copy Safari's last session state file to the "LastSessionTimeMachine"
# directory, with current date and time appended.
#
DATE=$(date "+-%Y-%m-%d-%H-%M-%S")
cp ~/Library/Safari/LastSession.plist \
    ~/Library/Safari/LastSessionTimeMachine/LastSession${DATE}.plist

# get a list of saved LastSession files, sorted newest to oldest
FILES=$(/bin/ls ~/Library/Safari/LastSessionTimeMachine/LastSession-*.plist | sort -r)

prevYear=0
prevMonth=0
prevDay=0
prevHour=0
prevMin=0
prevSec=0

# get current date
# note: fails if these commands are split across midnight
nowYear=$(date "+%Y")
nowMonth=$(date "+%m")
nowDay=$(date "+%d")

for AFILE in $FILES
do

    # parse filename into timestamp component
    timestamp=$(echo $AFILE | awk -F'[-\.]' '{print $2,$3,$4,$5,$6,$7}')

    # some weird code I found that parses a string into an array    
    set -- "$timestamp" 
    OLDIFS=$IFS; IFS=" "; declare -a Array=($*) 

    year=${Array[0]}
    month=${Array[1]}
    day=${Array[2]}
    hour=$Array
    min=${Array[4]}
    sec=${Array[5]}
        
    # delete file if we already have one from the same day but
    # skip today's files
    if [ "$year"  -eq "$nowYear"   -a \
         "$month" -eq "$nowMonth"  -a \
         "$day"   -eq "$nowDay"    ]; then
        echo "$timestamp is today's"
    elif [                            \
         "$year"  -eq "$prevYear"  -a \
         "$month" -eq "$prevMonth" -a \
         "$day"   -eq "$prevDay" ]; then
        echo "$timestamp is an older previous day's -- deleting"
        rm -f $AFILE
    else
        echo "$timestamp is newest from that day"
    fi
    
    prevYear=$year
    prevMonth=$month
    prevDay=$day
    prevHour=$hour
    prevMin=$min
    prevSec=$sec

done

exit 0



[ Reply to This | # ]