Advertisement

Terminal Tip: "Now Playing" info from the command line

Have you ever wondered whether there was a command line way to check iTunes and determine which song is currently playing. The command-line osascript utility makes this an easy problem to solve. Osascript executes AppleScript commands from Terminal's command line and can run many of the same kinds of simple scripts you'd normally run in Script Editor. Here's a quick how-to to build a Now Playing command line utility.

  1. Launch Terminal.

  2. In Terminal, enter: touch nowplaying

  3. In Terminal, enter: open -e nowplaying

  4. In TextEdit, paste the following into nowplaying. The second line wraps here but should copy and paste correctly--at least it did when I tried it out.
    #! /bin/bash
    osascript -e 'tell application "iTunes" to if player state is playing then "Now Playing: " & name of current track & " - " & artist of current track'

  5. Save the file in TextEdit and close it.

  6. In Terminal, enter: chmod 755 nowplaying

  7. Open iTunes and start playing a song.

  8. In Terminal, enter: ./nowplaying

The script, when run, outputs the track name and artist.

% ./nowplaying
Now Playing: Everything I've Got - Iain Archer
%

Thanks Dave M

%Gallery-2397%

Update: For those of you who don't want to keep iTunes open:
#! /bin/bash
osascript -e 'tell application "System Events" to if ((name of processes) contains "iTunes") then do shell script ("osascript -e " & quoted form of ("tell application \"iTunes\" to if player state is playing then \"Now Playing: \" & name of current track & \" - \" & artist of current track" & ""))'