Category Archives: Applescript

Controlling iTunes from the command line

I had a little fun the other day, making a script that would pause iTunes, from the command line. In the end I made ones to pause, play, and go forward a track.

All of them use a slightly modified version of a line of Applescript:

tell application “iTunes” to play

You can also tell it “to next track, to pause, to stop, to previous track”, which all work as expected.

To get it to work on the command line you’ll need to turn it into a script, which is a plain text file with some command line options in it. To get Applescript to work on the command line we need to use osascript, with the “-e” option.

Here’s what you should have in your file:

#!/bin/bash
osascript -e “Tell application “iTunes” to pause”

Note the the quotes and slashes? You need to wrap the Applescript command in quotes, and since you have quotes in the middle of it, you need to escape them using the slashes so the whole applescript is parsed.

Next step is to save the script to somewhere useful. In my case I have set my command line environment to check for scripts in ~/bin/ , so I saved it there as ‘pause’. After that you will need to make it an executable, so pop into the terminal and do “chmod +x ~/path-to-your-file/pause”, at which point you run it.

Go play something in iTunes, and then go over to the Terminal and type “pause” and hit enter. If your script is in your environment path then iTunes just paused…

Here are the other scripts I used, just to make your life easier ;-)

#!/bin/bash
osascript -e “Tell application “iTunes” to play”

#!/bin/bash
osascript -e “Tell application “iTunes” to next track”

Feedback is appreciated!

AppleScript 2.0!

Thanks to df for pointing out that Apple has posted release notes for AppleScript in Leopard.We can now ask if an application is running, without AppleScript launching it to find out. ;-)Some nice additions to running AppleScript on the Command Line:

  • use # to comment out a line
  • start the script with #!/usr/bin/osascript, and make it executable, will enable it to be run in the shell
  • osadecompile is a command line script to display compiled scripts as text

Now osascript also supports additional arguments on the command line, so now you can run a script and provide strings for it to use. see the osascript man page for details, and an example. This feature was available in Tiger, I just never noticed until now!