Advertisement

If and If Else: AppleScript Conditional Statements

by

Conditional statements are the backbone of many programming and scripting languages. In AppleScript, they provide a way for you to add another dimension of complexity to your scripts by analyzing and responding to various situations. This tutorial will take a close look at if and if else statements and the various ways to implement them in a script.


Diving Deep into AppleScript

Thus far we've posted two articles that are perfect for taking you from a complete novice to someone who can competently work your way around a basic script:

These tutorials serve as an overview and give you a good idea of how AppleScript works as well as what types of programming structures are involved. If you're really intent on becoming a master script writer though, you're going to have to go much deeper into the syntax and constructs that make up AppleScript.

Don't worry, we're with you every step of the way. This is the first in a series of articles that's going to take a long hard look at different aspects of AppleScript so that you can leverage its awesome power to automate your Mac.

Tip: To run the scripts in this post, you'll need to open the "AppleScript Editor" app, which can be found in Applications>Utilities.


What If?

In AppleScript, you'll be hard pressed to find two characters that rival the power of "if". If you learn to properly wield this seemingly simple tool, you'll go far.

A basic if statement works a lot like a tell block. Just for a refresher, here's the structure of a tell:

[applescript]
tell application "Safari"
activate
end tell
[/applescript]

As you can see, this script launches Safari. It has three lines: the first and last comprise the tell "block", which must always contain an end statement. Everything between these two lines makes up the body of the tell block.

Conditional statements, as well as many other constructs, borrow this same structure, only this time around we use if instead of tell.

[applescript]
if true then
--do something
end if
[/applescript]

This structure is pretty straightforward and should make perfect sense. First, you start your conditional statement and you qualify it with a boolean, then you write your commands that trigger in the case of a truth, and finally, you close off your statement with an end.

Anatomy of a conditional statement
Anatomy of a conditional statement

Tip: In AppleScript Editor, you don't need to type out "end if", just "end". The compiler will automatically add the rest, even if you have multiple end statements that belong to different types of blocks. It figures it all out for you!


Boolie What Now?

Before we go any further, it's absolutely critical that you understand exactly what I mean when I refer to a boolean. Boolean is a data type that can only have one of two values: true or false. In the world of computing, absolutes absolutely exist. Either something is, or it isn't, there's no in between.

AppleScript can easily figure out if certain things are true and use this knowledge to power a conditional statement. To try it out, try typing in an equality statement right into AppleScript Editor and running it.

True is returned
"True" is returned

As you can see, the compiler evaluated the statement, "10 > 1", and correctly returned "true". If we flip that equality symbol around and run "10 < 1", "false" is returned. This goes way beyond numeric expressions, pretty much any statement that AppleScript is able to evaluate should work as well. Here's a quick check of the current day of the week, which returns "true".

ApplScript can evaluate all kinds of different statements
ApplScript can evaluate all kinds of different statements.

How Conditionals Use Booleans

Now that you understand what a boolean is, it's easier to wrap your mind around how conditionals work. As we saw in the chart above, a conditional statement says, "if this boolean evaluates as true, then do something."

Let's see this in practice using the "10 > 1" statement that we tested earlier:

[applescript]
if 10 > 1 then
return "That's right!"
end if
[/applescript]

Here we've replaced the word "true" with something that we want AppleScript to evaluate. The structure here is exactly what we saw before:

ApplScript can evaluate all kinds of different statements
Breakdown of a conditional statement.

Given this structure, the commands inside of the if statement will only execute if the boolean proves to be true. In this case, the statement is true, so we'll see the following in the "Result" portion of the AppleScript Editor window.

ApplScript can evaluate all kinds of different statements
The script returned "That's right!"

Single Line Conditionals

In case you're wondering, there is a special, succinct form of an if statement that only occupies a single line. It does not require an "end" and can't take any of the added complexity that we're going to look at in the next section, but it's useful for simple cases.

[applescript]
--Single line if statement
if 10 > 2 then return "yes"
[/applescript]


Else

If statements are awesome, but they're a bit limited in the form that we've seen thus far. For instance, what if the boolean in the script turned out to be false? Here's an example:

[applescript]
set x to 20

if 10 > x then
return "10 is greater than " & x
end if
[/applescript]

As you can see, I'm gradually increasing the complexity here so that you become more familiar with common patterns and constructs. In this example, we first set up a variable, x, then set that variable equal 20. Now when we run our if statement, the number 10 is compared to the variable.

In this case, 10 is not greater than 20, so the boolean will be false. This means that our script won't do anything at all! To fix this problem, we turn to else. Let's modify our script a bit:

[applescript]
set x to 20

if 10 > x then
return "10 is greater than " & x
else
return "10 is not greater than " & x
end if
[/applescript]

The great thing about AppleScript is that it's so human readable. If you simply read this script out loud, you'll be able to tell exactly what it does. Here's the rundown:

  • Assigns a value of 20 to x
  • Compares the number 10 to x to see if 10 is greater
  • If 10 > x, return the following statement
  • If not (else), return this other statement instead

Given that 10 is not greater than 20, the second statement will be returned. Your result should look something like this:

ApplScript can evaluate all kinds of different statements
The script returned "That's right!"

Now that we can account for two different boolean scenarios, we are much more suited to tackle complex scripting challenges.

Else If

As you can imagine, even this isn't enough to account for all of the different situations that you're going to run into. Perhaps we have a fairly complex scenario that where a number of different outcomes is possible.

In this scenario, we can implement else if to continue adding complexity to our if statement. Consider the following:

[applescript]
set theWeekDay to weekday of (current date)

if (theWeekDay = Friday) then
return "You're almost free!"
else if (theWeekDay = Saturday) then
return "It's the weekend!"
else if (theWeekDay = Sunday) then
return "Relax, for tomorrow we work."
else
return "Hang in there, it's not the weekend yet!"
end if
[/applescript]

Once again, even if you're not familiar with AppleScript, the natural language makes it pretty easy to figure out what's going on. First, we set a variable to the current weekday. Next, we run through a series of tests using if, else if and else to arrive at an appropriate return message given the current day of the week.

ApplScript can evaluate all kinds of different statements
"Else if" in action.

On run, the script will try the first if statement. If that proves true, the first return statement will be run and the script will terminate (no further steps are taken). However, if that statement proves false, the first else if is tried, then the second and finally, if none of those prove true, the last else kicks in and returns a statement about it not being the weekend yet.

Leaner Code is Better

The else if structure is incredibly powerful and allows you to account for any number of different scenarios. As you code up certain projects, you might be tempted at times to chain together five, ten or even fifteen else if statements to cycle through all of the available possibilities. Unfortunately, this isn't typically a good way to code and can lead to a ton of unneeded bloat.

Always be mindful when using else if and ask yourself whether or not there's a better way to go about what you're trying to accomplish. It's often far more practical and brief to use a loop of some kind, but that's an article for another day (coming soon!).

This or That?

One last quick piece of advice regarding if statements. One alternative to else is to use or instead. Here's a simplified version of the weekday script using or and only two possible return statements.

[applescript]
set theWeekDay to weekday of (current date)

if (theWeekDay = Saturday) or (theWeekDay = Sunday) then
return "It's the weekend!"
else
return "Hang in there, it's not the weekend yet!"
end if
[/applescript]

Stay Tuned

This covers most of what you need to know about conditionals. Crack open AppleScript Editor and start experimenting with your own conditional statements. What cool scripts can you come up with?

This is just the tip of the proverbial iceberg as far as our coverage of AppleScript. This is an incredibly expansive topic that has a lot of potential to increase your mastery over your Mac, so we're going to have lots more great AppleScript tutorials to help you become a true automation expert.

Advertisement