August 17, 2009

iTunes Syncing, Part 2

In my prior posting, I set up a script to handle the syncing of my iTunes library between my home system and the carputer. The script works fine, but executing it via the Terminal is a pain. With OS X, it is possible to rename a shell script with an extension of .command, which will allow it to be double clickable in the Finder, but this unfortunately will cause Terminal to launch, show the output, and then leave the Terminal window open when the script finishes. There are a few hacks to get around this, but the most common solution I've found is to instead call the shell script via AppleScript. As usual, this has caused a few additional headaches...

The AppleScript portion is extremely straightforward. Open Script Editor, and paste in the following:

-- do our sync
do shell script "~/Documents/Scripts/ &> /dev/null &"

Save this as an Application, and we're done. The line above will execute out script, and spawn this as a separate process, meaning that AppleScript won't be waiting for the script to finish, it will kick it off, and the AppleScript will then quit.

The headache I ran into is that the pmset command wasn't quitting like it should have, the issue turned out to be that the process for that was no longer able to be found by the ps command, because the script was now being launched via AppleScript and not directly via the Terminal. The solution was to use ps -e instead, so the working script is now as follows:


# this command will keep the system from going to sleep, spawns a new processes
`pmset noidle` &
# get pid of the pmset process so we can kill it later
pid=`ps -e | grep [p]mset | awk '{print $1}'`

# set the log file to be placed in user's home directory

ping -c 1 $SERVER > /dev/null 2>&1
if [ $? -ne 0 ]
echo `date '+%m/%d/%Y %T - '` "server unreachable" >> $theLog
echo `date '+%m/%d/%Y %T - '` "server found" >> $theLog
rsync -avz $USER@$SERVER:Music/iTunes/ ~/Music/iTunes >> $theLog

echo `date '+%m/%d/%Y %T - '` "Done" >> $theLog

# need to kill pmset we spawned earlier so system will sleep
echo `date '+%m/%d/%Y %T - '` "killing $pid" >> $theLog
kill -9 $pid >> $theLog

# Now tell system to go to sleep since we're done
pmset sleepnow >> $theLog

Posted by Jim at August 17, 2009 12:09 PM | TrackBack