Using Bash to update Twitter with the current playing track in iTunes

by Stii

Bash can do everything. From curing cancer right up to making you look cool :) I wanted to update Twitter when I listen to something very, very cool like Tom Waits.

This Bash script gets the info of the current playing track from iTunes using the osascript command (osascript executes AppleScript, so naturally, this is for OSX ;-) ) and tweets it using curl. I had to use Perl to encode the update string since characters like & was not behaving kind! :) Here it is:

#!/bin/sh

state=`osascript -e \
'tell application "iTunes" to player state as string'`;
if [ $state = "playing" ]; then
        artist=`osascript -e \
        'tell application "iTunes" to \
        artist of current track as string'`;
        track=`osascript -e \
        'tell application "iTunes" to \
        name of current track as string'`;
        album=`osascript -e \
       'tell application "iTunes" to \
       album of current track as string'`;
        msg="Listening to $track by $artist from $album";
        curl --basic --user "username:password" \
        --data-ascii "status=`perl -MURI::Escape -e \
        "print uri_escape('$msg');"`" \

http://twitter.com/statuses/update.json

fi

I saved it in a script called tweettune and

chmod 755 tweettune

to make it executable. If you run the script it will return the update in JSON format.

It works great. If you are cooler and your Bash is hotter than mine, please send/leave me the code to try!

PS: remember to replace username:password with your Twitter login credentials.
PPS: Yes, I know OAuth for Twitter is out. This is not about using OAuth, but updating your Twitter status with the current track playing in iTunes.