TweetFollow Us on Twitter

Using Repeat Loops in AppleScript

Volume Number: 20 (2004)
Issue Number: 12
Column Tag: Programming

AppleScript Essentials

by Benjamin S. Waldie

Should I Repeat Myself?

Using Repeat Loops in AppleScript

For the past couple of months, we have been talking about some basic Finder scripting. Now we are going to switch gears and get back to some basics of AppleScript. In this month's article, we will discuss the various types of repeat loops that you can use when you are scripting.

Why You Need Repeat Loops

Repeat loops are invaluable when writing AppleScript code, because you will frequently need to perform a single task more than once. While in some cases, you could simply write the same code over and over again in order to achieve the same result, in other instances, you cannot.

For example, let's say that you have a folder containing 10 files, and you want to rename all of them with a unique numeric extension from 1 to 10. You could write a repetitive AppleScript that would rename the files in this manner without a repeat loop. However, why would you want to do that? It would take a while to write, and it would be kind of a pain in the neck if you wanted to go back and change the code. For example, what if, after writing the code, you changed your mind and now you want the files to be named from 11 to 20? You would need to go back through all of your code and restructure it. Isn't one of the primary functions of AppleScript to automate things? So, why not automate your code?

In some cases, the only way to accomplish a task is to use a repeat loop. For example, let's say that you need a script that will rename files in a folder. However, the number of files in the folder may change each time the script is run. To do this, you would need to get a list of all of the files in the folder, and then use a repeat loop to go through and rename all of them.

As we continue, throughout this article, you will see how repeat loops can be extremely useful in all types of automated processes.

Types of Repeat Loops

There are several different types of repeat loops that can be used in AppleScript.

Repeat

In AppleScript, it is possible to loop indefinitely by using the repeat type of repeat loop, which is written as follows:

repeat
   -- DO SOMETHING
end repeat

Using the above example, the AppleScript code inside of the repeat loop will loop on forever. It will never stop unless an error occurs. You should take care when using this type of repeat loop, as you can sometimes box yourself into a corner with no way to get out. It is always good practice to provide some type of mechanism within your code in order to get yourself out of the repeat loop. This is typically done by using the exit repeat statement.

For example, let's say that you need to display a dialog prompting the user to enter a username. However, you want to make absolutely sure that the user types at least something into the dialog. This can be done with a combination of a repeat type of repeat loop and an exit repeat statement.

repeat
   display dialog "Please enter your username:" default answer ""
   set theUserName to text returned of result
   if theUserName <> "" then exit repeat
end repeat

As you can see in the example code above, the dialog will continue to be displayed until the user enters something into the prompt.

Repeat Times

Another type of repeat loop in AppleScript is the repeat times type of repeat loop, which is used to perform a loop for a specified number of times. For example, let's use the same scenario as above. However, instead of looping forever, let's say that you want to only give the user 3 chances to enter the username before an error will occur.

repeat 3 times
   display dialog "Please enter your name:" default answer ""
   set theUserName to text returned of result
   if theUserName <> "" then exit repeat
end repeat
if theUserName = "" then display dialog "Invalid Entry!!!"

In the example code above, the user will only be prompted to enter the username a maximum of 3 times. If the user does not enter a username, then an error notification will be displayed.

Repeat While

The repeat while style of repeat loop is typically used to test for a specific scenario to occur. For example, we could use the repeat while type of repeat loop as another way to verify that a user enters something into our dialog example.

set theUserName to ""
repeat while theUserName = ""
   display dialog "Please enter your name:" default answer ""
   set theUserName to text returned of result
end repeat

In the example above, the script will continue to loop until something is entered into the dialog. You could also use a repeat loop of this nature to loop until a file is detected in a certain folder. For example:

set theFilePath to (path to desktop as string) & "test.psd"
tell application "Finder"
   repeat while (file theFilePath exists) = false
   end repeat
end tell
display dialog "The Photoshop file has arrived!"

Repeat Until

The repeat until type of repeat loop is yet another type of repeat loop that is used to test for specific scenarios to occur. As you can see in the example code below, this type of repeat loop is very similar to the repeat while type of repeat loop.

set theUserName to ""
repeat until theUserName <> ""
   display dialog "Please enter your name:" default answer ""
   set theUserName to text returned of result
end repeat

Reprat With

The repeat with type of repeat loop can actually be broken down another level, into two separate types of distinct repeat with loops.

The first type of repeat with loop will allow you to loop for a specified number of times, while dynamically incrementing an integer variable's count. This type of repeat with loop is formed as follows:

repeat with theIncrementValue from theStartingValue to theEndingValue
   -- DO SOMETHING
end repeat

In the code above, the variable theIncrementValue signifies the current increment of an integer value in the loop. The variable theStartingValue signifies an integer that should be used as the initial increment value, whereas the variable theEndingValue signifies an integer that should be used as the final increment value. When a repeat loop of this nature is executed, it will continue to loop, incrementing the variable theIncrementValue each time until it reaches the value of the theEndingValue.

Let's take a look at another example in order to help illustrate this process. In the following example, we are going to prompt the user to select a folder, and then loop a specified number of times, building a folder for each increment.

set theDestinationFolder to choose folder
tell application "Finder"
   repeat with theIncrementValue from 1 to 10
      make new folder at theDestinationFolder with properties {name:theIncrementValue as string}
   end repeat
end tell

When executed, the code above will generate 10 folders, named from 1 to 10, in a user specified directory. You can see how using a repeat loop for this type of task can help to make your AppleScript code extremely efficient.

It is also possible to change the manner by which the increment in this type of repeat loop occurs. For example, you may not want to loop by 1's. Instead, you may want to loop by 2's. This can be done by adding an optional by parameter at the end of the initial repeat with statement. For example:

set theDestinationFolder to choose folder
tell application "Finder"
   repeat with theIncrementValue from 1 to 10 by 2
      make new folder at theDestinationFolder with properties {name:theIncrementValue as string}
   end repeat
end tell

In the example above, the script increments by 2's rather than 1's. Therefore, instead of building 10 folders, the script will only build 5, and they will be named "1", "3", "5", "7", and "9".

When using this type of repeat with loop, it is not necessary to begin the loop with a starting increment of 1. For example, the following code will cause 10 folders to be created, named from 11 to 20.

set theDestinationFolder to choose folder
tell application "Finder"
   repeat with theIncrementValue from 11 to 20
      make new folder at theDestinationFolder with properties {name:theIncrementValue as string}
   end repeat
end tell

It is also possible to cause the increment value to move in reverse, such as from 10 to 1. For example:

set theDestinationFolder to choose folder
tell application "Finder"
   repeat with theIncrementValue from 10 to 1 by -1
      make new folder at theDestinationFolder with properties {name:theIncrementValue as string}
   end repeat
end tell

At the beginning of this section, I mentioned that there are actually two types of repeat with loops in AppleScript. The second type of repeat with loop is used to loop through a series of values in a list. It is formed as follows:

repeat with theCurrentValue in theListOfValues
   -- DO SOMETHING
end repeat

When using this type of repeat with loop, each time the code loops, the variable theCurrentValue will take on the value of the current item in the list variable theListOfValues. Let's take a look at this type of loop in action.

set theDestinationFolder to choose folder
set theListOfValues to {"apples", "oranges", "pears"}
tell application "Finder"
   repeat with theCurrentValue in theListOfValues
      make new folder at theDestinationFolder with properties {name:theCurrentValue}
   end repeat
end tell

In the example code above, the script will loop through the list variable theListOfValues, which, in this case, contains the names of three different types of fruit. Each time the code loops, the variable theCurrentValue will take on the current value from the variable theListOfValues. So, during the first loop, the variable theCurrentValue would take on a value of "apples", the second loop, it would take on a value of "oranges", and so forth.

In Closing

Hopefully, the various types of repeat loops specified in this article will be helpful to you as you begin writing more complex AppleScript code. By creating nested repeat loops of varying types, you can really create some complex and adventurous scripts.

If you are interested in learning more about repeat loops in AppleScript, I recommend checking out the AppleScript Language Guide, which can be found under AppleScript in the Developer Connection on Apple's web site - http://developer.apple.com/. You may also want to consider picking up a good introductory AppleScript book, such as Danny Goodman's AppleScript Handbook.

Until next time, keep scripting!


Benjamin Waldie is president of Automated Workflows, LLC, a firm specializing in AppleScript and workflow automation consulting. In addition to his role as a consultant, Benjamin is an evangelist of AppleScript, and can frequently be seen presenting at Macintosh User Groups, Seybold Seminars, and MacWorld. For additional information about Benjamin, please visit http://www.automatedworkflows.com , or email Benjamin at applescriptguru@mac.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Hopper Disassembler 4.5.0- - Binary disa...
Hopper Disassembler is a binary disassembler, decompiler, and debugger for 32- and 64-bit executables. It will let you disassemble any binary you want, and provide you all the information about its... Read more
Adobe Acrobat Reader 19.010.20064 - View...
Adobe Acrobat Reader allows users to view PDF documents. You may not know what a PDF file is, but you've probably come across one at some point. PDF files are used by companies and even the IRS to... Read more
Airmail 3.6.53 - Powerful, minimal email...
Airmail is an mail client with fast performance and intuitive interaction. Support for iCloud, MS Exchange, Gmail, Google Apps, IMAP, POP3, Yahoo!, AOL, Outlook.com, Live.com. Airmail was designed... Read more
iFinance 4.5.4 - Comprehensively manage...
iFinance allows you to keep track of your income and spending -- from your lunchbreak coffee to your new car -- in the most convenient and fastest way. Clearly arranged transaction lists of all your... Read more
Microsoft Office 365, 2019 16.20 - Popul...
Microsoft Office 365. The essentials to get it all done. Unmistakably Office, designed for Mac Get started quickly with new, modern versions of Word, Excel, PowerPoint, Outlook and OneNote-... Read more
Microsoft Remote Desktop 10.2.4 - Connec...
With Microsoft Remote Desktop, you can connect to a remote PC and your work resources from almost anywhere. Experience the power of Windows with RemoteFX in a Remote Desktop client designed to help... Read more
Spotify 1.0.95.289 - Stream music, creat...
Spotify is a streaming music service that gives you on-demand access to millions of songs. Whether you like driving rock, silky R&B, or grandiose classical music, Spotify's massive catalogue puts... Read more
Dropbox 63.4.100 - Cloud backup and sync...
Dropbox is an application that creates a special Finder folder that automatically syncs online and between your computers. It allows you to both backup files and keeps them up-to-date between systems... Read more
Little Snitch 4.2.4 - Alerts you about o...
Little Snitch gives you control over your private outgoing data. Track background activity As soon as your computer connects to the Internet, applications often have permission to send any... Read more
Skype 8.36.0.52 - Voice-over-internet ph...
Skype allows you to talk to friends, family and co-workers across the Internet without the inconvenience of long distance telephone charges. Using peer-to-peer data transmission technology, Skype... Read more

Latest Forum Discussions

See All

148Apps year end round-up: These are the...
We've reached the fifth month of the year in our round-up of all of the top games for iPhone and iPad that came out in 2018. If you've missed the other entries in this massive list, don't you worry, because we're going to give you links to them all... | Read more »
148Apps year end round-up: These are the...
Oh hi there, and welcome to the fourth part of our series about the very best iPhone and iPad games that came out in 2018. We've made it to April, which is when Fortnite came out. So, yeah, Fortnite is at top of this part of the list. Not really a... | Read more »
148Apps year end round-up: These are the...
It's Monday, and our round-up of the best games of 2018 has landed on March. There were some pretty amazing developments in the third month of the year, mainly thanks to the launch of PUBG and the start of the Fortnite beta (technically Fortnite... | Read more »
Twinfold guide
Twinfold may look like a cheap Threes! clone at first glance, but it's so much more than that. It's actually a rather deep roguelite with a really satisfying difficulty curve and almost endless replayability. Since the game's depth does take some... | Read more »
Which of these iPhone and iPad games sho...
On a normal week we like to give you the chance to vote for your game of the week on Thursday. But since this clearly isn't a normal week, we've decided to give you the chance to vote for our game of the week on Friday. You're welcome. [Read more... | Read more »
Munchkin.io ends 2018 in style with a ne...
While it can sometimes seem like we are drowning in a sea of battle royale games, few struggle to actually deliver the kind of fun and frantic experience you’d expect from a refined entry in the genre. Well step aside from those other games because... | Read more »
Choose a side in Rift of Raigard, the ne...
If you’re an RTS player that’s constantly underwhelmed by most genre entries on mobile, or sick of putting up with stingy F2P models and cheaters, Rift of Raigard is the base building game for you. Developed by a team of creators who are equally... | Read more »
148Apps year end round-up: These are the...
Our round up of the best games of the year has rolled along to February. Which makes sense, since we started off with January - click here and you'll be able to read the top 5 in its entirety - and February was definitely a doozy, we can tell you... | Read more »
The top 5 best gifts for mobile gamers t...
Since it's the most wonderful time of the year according to most adverts, and since the most wonderful time of the year is all about the giving and receiving of presents (and probably some other stuff, we guess), we thought it was high time we... | Read more »
Dragalia Lost - Resplendent Refrain Sabn...
Dragalia Lost's latest event, Resplendent Refrain, is an event that favors light Adventurers in an all new raid dungeon. This dungeon has four teams of four face off against the mighty Sabnock, which is probably the toughest raid fight in the game... | Read more »

Price Scanner via MacPrices.net

Get a 2017 12″ MacBook for $200-$240 off MSRP...
Apple has Certified Refurbished 2017 12″ Retina MacBooks available for $200-$240 off the cost of new models. Apple will include a standard one-year warranty with each MacBook, and shipping is free.... Read more
Two weeks until Christmas, and B&H contin...
B&H Photo has new 13″ MacBook Pros on sale for up to $200 off MSRP as part of their Holiday 2018 sale. Their prices are the lowest available for new 13″ MacBook Pros from any Apple reseller.... Read more
Apple Watch Series 3 sale! Get a GPS only mod...
Get an Apple Watch Series 3 GPS only model for $50 off MSRP today on Amazon, with 38mm Watches starting at only $229. Shipping is free: – 38mm Apple Watch Series 3 GPS only: $229 $50 off MSRP – 42mm... Read more
Flash deal: Apple HomePods for $249 at B&...
B&H Photo has Apple HomePods on sale for $249 as part of their Holiday 2018 sale. Their price is $100 off Apple’s price and the lowest available from any Apple reseller. Shipping is free: –... Read more
12″ 1.2GHz Space Gray MacBook on sale for $11...
B&H Photo has new 2017 12″ 1.2GHz Space Gray MacBooks on sale for $150 off MSRP this week, just $1149. Shipping is free: – 12″ 1.2GHz Space Gray MacBook: $1149 $150 off MSRP Amazon lowered their... Read more
Roundup of Sprint Holiday 2018 sales: Deals o...
Sprint is offering a number of deals this Holiday 2018 season on Apple products, including the new 2018 iPhones, Apple Watch Series 4, and 9.7″ iPad: – $100 off an Apple Watch Series 4 when you add a... Read more
$190-$200 off on iPhone 6s & 6s Plus at T...
Total Wireless is offering the iPhone 6s starting at $199.99 through December 31, 2018. Sale prices are available on the following models: – $100 OFF on the 32GB iPhone 6s, now $199.99, free shipping... Read more
B&H offers clearance 2017 MacBook Airs fo...
B&H Photo has clearance 2017 13″ 1.8GHz MacBook Airs on sale for up to $200 off MSRP, with models available starting at $869. Shipping is free: – 13″ 1.8GHz/128GB MacBook Air (MQD32LL/A): $869, $... Read more
Get last year’s 10.5″ iPad Pro, Certified Ref...
Apple has Certified Refurbished 2017 10.5″ iPad Pros available for $100-$170 off original MSRP, depending on the model. An Apple one-year warranty is included with each model, and shipping is free... Read more
Apple still offering Certified Refurbished 9....
Apple has Certified Refurbished 2016 9.7″ iPad Pros available starting at $469. An Apple one-year warranty is included with each model, and shipping is free: – 32GB 9″ iPad Pro WiFi: $469 original... Read more

Jobs Board

*Apple* Systems Specialist - Western Washing...
Apple Systems Specialist Apply now Work type: Permanent Full Time Location: Bellingham, WA Categories: Academic Affairs Position Title Apple Systems Specialist Read more
Senior Desktop Support Technician, *Apple*...
**Requisition ID** 18-1384 **Job Title** Senior Desktop Support Technician, Apple Support **Location** New York **Schedule** Full-time **Type of Position** Regular Read more
Best Buy *Apple* Computing Master - Best Bu...
**660853BR** **Job Title:** Best Buy Apple Computing Master **Job Category:** Store Associates **Location Number:** 001406-Allen Park-Store **Job Description:** The Read more
*Apple* Mobile Master - Best Buy (United Sta...
**660896BR** **Job Title:** Apple Mobile Master **Job Category:** Store Associates **Location Number:** 001017-San Angelo-Store **Job Description:** **What does a Read more
Sephora Product Consultant - *Apple* Blosso...
Sephora Product Consultant - Apple Blossom Mall Location:Winchester, VA, United States- Apple Blossom Mall 1850 Apple Blossom Dr Job ID:1056553 Date:Yesterday Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.