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
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 tellClick 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.
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 tellClick 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
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 tryClick 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