Subscribe / Unsubscribe Enewsletters | Login | Register

Pencil Banner

Introduction to AppleScript: What you can do with AppleScript, OS X's scripting language

Kenny Hemphill | Aug. 31, 2015
Understand and get more from AppleScript.

Easy, huh? Sadly not all AppleScriptable applications support recording and those that don't allow you to record every action. Often the only way to find out if an app is recordable and what it allows you to record is to try it.

Macworld UK. Mail allows interaction via AppleScript

Write an ApplScript script yourself

A better solution, then, is to write the script yourself. Thankfully, it's not too difficult, once you've learned the basics of AppleScript's syntax.

The first thing you need to do in any AppleScript is 'tell' it what application you want to use. Handily, this, like most AppleScript commands, is done inside a 'tell' block. So, in the example above, the script for creating 'My New Folder', we start with:

tell application "Finder"

Commands in AppleScript are, as far as possible, plain English, making them relatively easy to read and write. There are, however, rules to be adhered to, otherwise your script won't compile. One of those is that every 'tell' block must end with 'end tell.'

So the complete script for our example of making a new folder on the desktop called 'My New Folder' is this:

tell application "Finder"
make new folder at desktop with properties {name:"My New Folder"}
end tell

The make command can also be used to create files and aliases. And by changing 'desktop' and "My New Folder" to whatever you want, you can change the location and the name of the folder.

Variables in AppleScript

Variables in AppleScript do the same job as they do in other scripting and programming languages - they store data so you can call on it later. The data can be specified in the code or it can be the result of a calculation or user input. So, in our folder example, we could declare variables for the name and location of the folder like this:

set folderName to "My New Folder"
set folderLocation to desktop

After declaring the variables, we'd write the script like this:

tell application "Finder"
make new folder with properties {name:folderName, location:folderLocation}
end tell

In this example, declaring and using variables doesn't help us because the variables are only used once and so the effort in creating them outweighs the benefit. Where you need to use the same data multiple times, however, declaring variables at the start means that if you wanted to change, in this example, either the name or the location of the file, you'd only need to change one line of code for each variable, rather than every instance of that variable. And where a section if script takes the output from a previous calculation or user interaction, using variables is essential.

Organising scripts in AppleScript


Previous Page  1  2  3  Next Page 

Sign up for CIO Asia eNewsletters.