EDDYMENS

Published 3 months ago

MacOS AppleScript Tutorial: Part 3 - Loops, Conditional Statements, And Error Handling

Table of contents

In Part 2 [β†’], we learned how to control apps and get information from them. In this part, we will cover more advanced concepts like loops, conditional statements, and error handling.

Using Conditional Statements

Conditional statements allow your script to make decisions. We have already seen an example [β†’] with the if statement. Let’s look at another example:

Example: Checking for a Specific File

  1. Type the following into Script Editor:

    01: tell application "Finder" 02: if exists file "MyDocument.txt" of desktop then 03: display dialog "File found!" 04: else 05: display dialog "File not found!" 06: end if 07: end tell
  2. Click Run.

This script checks if a file named "MyDocument.txt" exists on your desktop and displays a message accordingly.

Loops in AppleScript

Loops let you repeat actions. For example, let’s rename all the files on your desktop by adding "Old_" to the beginning of each file name.

  1. Type the following into Script Editor:

    01: tell application "Finder" 02: set theFiles to every file of desktop 03: repeat with aFile in theFiles 04: set name of aFile to "Old_" & name of aFile 05: end repeat 06: end tell
  2. Click Run.

This script goes through each file on your desktop and renames them.

Breaking Down the Script

  • set theFiles to every file of desktop gets a list of all files on your desktop.
  • repeat with aFile in theFiles loops through each file in that list.
  • set name of aFile to "Old_" & name of aFile renames each file by adding "Old_" to the beginning.

Error Handling

Sometimes, scripts may fail due to unexpected errors (e.g., a file is missing). You can handle errors using a try block.

Example: Error Handling for a Missing File

  1. Type this in Script Editor:

    01: try 02: tell application "Finder" 03: delete file "NonExistentFile.txt" of desktop 04: end tell 05: on error 06: display dialog "The file doesn't exist!" 07: end try
  2. Click Run.

In this example, if the file "NonExistentFile.txt" is missing, the script will show a message instead of crashing.


Conclusion

In Part 3, you learned how to:

  • Use conditional statements to make decisions in your scripts.
  • Write loops to repeat actions.
  • Handle errors gracefully when things go wrong.

In the next part of the tutorial, we’ll dive into more complex workflows and show how AppleScript can help you build real-world automations.

Here is another article you might like 😊 MacOS AppleScript Tutorial: Part 2 - Interacting With Apps And Getting Data