AppleScript Programming/Basic commands

From Wikibooks, open books for an open world
Jump to navigation Jump to search

AppleScript is a programming language that is somewhat similar to English making it easier to understand than some programming languages. The commands in AppleScript are written in a syntax similar to English. This allows users more easily understand the code.

A first script[edit | edit source]

Alright, let's write our first program! Launch your Script Editor application (in /Applications/Applescript [pre OSX 10.5] or /Applications/Utilities [OSX 10.5 or later]) and type this into your new document:


Then hit the run button.

Shortest applescript.png

Your Mac should now play its default beep sound. You have just learned your first AppleScript command: beep. The above script is the shortest script in AppleScript, or at least the shortest that does something.

Dialog boxes[edit | edit source]

But if you're going to write a tool for scripting programs or even a small AppleScript program, you're going to need to learn to do more than to make the computer beep. The next command we will explore is "display dialog". A display dialog command is written like this:

display dialog "the text to display goes here"

This can be used to present information to a user or, as you will find out later, ask for it.

Setting variables[edit | edit source]

Another vital command you should learn is the "set" command. The "set" command sets variables to strings, lists, records, and other variable types. Here is a set command in action:

set theVariable to "Support Wikibooks!"

Now, if one wanted to show the user what the text stored in variable "theVariable" was, they could type:

display dialog theVariable

A dialog box would appear with the text "Support Wikibooks!"

Now you know three vital commands and were briefly introduced to strings. More information on strings is in the next module.

Using variables with strings[edit | edit source]

You can use a variable and a string in the same display dialog line. They are combined with &

set project to "Wikibooks"
display dialog "Support " & project

Exercises[edit | edit source]

Create a program says "Hello [your name]" with [your name] in a variable.