how to remove the System Preferences Badge app icon (Catalina Upgrade)

If you’re not ready to upgrade to macOS Catalina yet – and there’s good reasons why you might want to hold off – you might also be tired of seeing the red update badge in the System Preference’s Dock icon in macOS Mojave and the ‘Upgrade Now’ advert in the Software Update pane. Also, there’s a similar badge polluting you with more unwanted visual noise every time you open System Preferences main view itself.

image of system preferences update badge

Unlike other applications in the Notifications preferences pane, there’s no entry for the System Preferences app itself where you can turn off the Badge app icon.

I know there are those that will deliberately run their Macs at least one major version behind the current version (though I can think of multiple security reasons why that’s not a good idea) and others who don’t want to update at all. Aside from those wanting to avoid the expense of their current 3rd party software demanding “pay-me for a new Catalina-compatible version”, there are those still using incompatible 3rd party kexts, 32-bit apps or who are just happy with the features and performance they’re currently enjoying.

Are they all condemned to having the annoying update notifications in their faces until they surrender to Apple’s will?

Fortunately not, but there are three different places the nags appear, and depending on how obsessive you are about not seeing the update and badge icons, you may or may not want to deploy some or all of the tricks described below. There’s a couple of things to watch out for, too, so if you do choose to implement any of these workarounds, remember to bookmark this page for future reference when you want to undo any of the changes you made.

1. Remove the Catalina Advert Inside Software Update

image of catalina upgrade advert

If all you want to do is stop Catalina appearing in the Software Update pane urging you to “Upgrade Now”, you can use this super tip from Macadmin guru Rich Trouton. It’ll require a trip to the Terminal.app (/Applications/Utilities/Terminal.app) and an administrator’s password.

From the command line, copy and paste the following:

sudo softwareupdate --ignore "macOS Catalina"

Hit ‘return’ and type your admin password, which will be invisible when you do so.

After completing this step, you’ll no longer see Catalina advertized, but you’ll still have the red number “1” badge in both System Preferences and the Dock.

Gotchas and How to Undo

The main gotcha to remember after doing this is you won’t see Catalina updates, and even if you go to the App Store and try to “get” it, it will fail to install.

To reverse the above step, go back to the Terminal and use:

sudo softwareupdate --reset-ignored

2. Remove the Badge on the Dock Icon

If you keep System Preferences in the Dock, you’ll notice that even after the previous step you still have the eye-catching red banner alert on the Dock.

I’ve seen some suggestions of using a defaults command to try to address this, but it appears to be a temporary fix and has to be repeated every time you open Software Update, so I don’t recommend this particular trick.

defaults write com.apple.systempreferences AttentionPrefBundleIDs 0; killall Dock

A better way to rid yourself of it is by replacing System Preferences in the Dock with an alias to the app instead.

image of making an alias

In the Finder, navigate to the /Applications folder, right-click on System Preferences and choose ‘Make Alias’. Now add the alias to the Dock by dragging it from the Finder into place on the Dock. Remove the original System Preferences Dock icon by dragging it from the Dock to the centre of your screen.

image of replace system preferences dock icon

Gotchas and How to Undo

The main gotcha with this one is that you won’t see the update badge for other updates that may be relevant to your current install, so you’re going to need to develop the habit of making a regular check. A weekly or fortnightly Reminder or Calendar alert could be useful here. While that might seem like you’re replacing one notification with another, at least it would be one that will leave you in peace during whatever interval you set between reminders.

Undoing the workaround is as simple as removing the alias from the Dock and replacing it with the original. Of course, if you’re done with the alias don’t forget to delete it from the Applications folder, too.

If you happened to try the defaults workaround, the way to reverse that is with the same command but replacing the 0 with a 1.

3. Removing the Badge Icon in System Preferences Pane

This is the trickiest one, as in fact there is no way to keep the icon in the pane without the badge. What we can do, however, is hide the icon entirely. That doesn’t mean we lose access to Software Update, however, as I’ll explain below.

To hide the icon, go to the View menu and choose “Customise”.

image of customise system preferences

Unclick the checkbox next to “Software Update” and click “Done” at the top. You’ll now see that the Software Update icon is no longer shown.

In order to run a check for new software, just begin typing “software” in the search filter and click on either “Software Update” or “Check for Software Updates”. Alternatively, you can go to System Preferences’ View menu at the top of the screen and choose ‘Software Update’ from the menu list.

image of check for software updates

Gotchas and How to Undo

The main “gotcha” here is that you might easily forget that you’ve hidden the pane and might also forget to check for updates. As always, it’s a good idea to have “Check for updates automatically” turned on with security updates set to install to avoid missing out on any important security and bug fixes.

To reverse, just go back to the Customise option in the View menu, and re-enable the checkbox.

Conclusion

If after reading all that you’re thinking: “my word, what a pallava, I’m not sure I’ll bother!” you may well be thinking exactly what Apple want you to think. Of course, Apple are heavily invested in ensuring users move up to the latest version of macOS as soon as possible, and the difficulty of avoiding that and the “nags” and nuisance badges is not accidental. Whether you decide to go along with Apple or hold out for your own reasons is entirely your choice, but the irritation or inconvenience you might experience with going with the latter option isn’t something Apple are going to lose sleep over, I’m afraid!

Enjoy! 🙂


21 macOS & iOS Twitter Accounts You Should Be Following

image of bird on branch

With Apple’s signature developer event WWDC 2019 just around the corner, it’s a good time to think about your Apple-related Twitter feeds from an IT and security-related perspective. Are you keeping up with all the news that Apple want you to know about and (maybe!) some they don’t, like bugs, vulnerabilities and exploits?

In this post, we offer a curated list of all the best macOS and iOS related Twitter accounts to make sure you don’t miss a thing.

Continue reading…


how to remove MyCouponsmart on macOS

The adware plague on macOS continues, and if you’re one of the thousands that have caught something unwanted when you downloaded some other program, this post should help. I’ll explain what MyCouponsmart is, what it does, and how you can remove it, either yourself or with a simple and free shareware program I develop.

What is MyCouponsmart?

Like MyCouponize, TotalAdviseSearch, DigitalChannel Search and many others, MyCouponsmart is one of a host of “search offer” programs that either redirect or inject your web browser with ads when you make an internet search. You may have been looking for some kind of media downloader or media player, like Adobe’s Flash, and inadvertently end up with a bunch of unwanted programs like MacKeeper, Mac Auto Fixer, Advanced Mac Cleaner or some other similarly named “performance” app.

Typically, these programs will take over your browser, showing scare pages like the following:

image of scare ware advert

Hmm, it looks like my computer has got plenty of free space available, thank you very much!

image of free disk space

That’s no surprise, really. Webpages cannot tell you how much free space is on your local drive, nor can they scan your drive and “detect infections” as some other scare pages want users to believe.

All such warnings are entirely fake and tell you only that you have some kind of adware infection in your browser! The people behind the ads bank on the fact that many users do have full drives, so when they check they are fooled into believing the advertised product can help them.

Similarly, many users who see these kind of scare adverts offering fake Anti-virus software often do indeed have malware on their computer: the malware that’s causing the advert to appear!

Needless to say, none of these advertised programs are worth your money.

What does MyCouponsmart do?

Let’s take a look inside your user Library. This is hidden by default, but you can get to it from the Finder’s “Go” menu. Click on the Finder then use the keyboard combination

Command-Shift-G

find user library folder macOS

Type in, or copy and paste, the following, and be sure not to miss that tilde ~ at the beginning, or you’ll end up in a different place:

~/Library/LaunchAgents

This is the LaunchAgents folder. There’s actually more than one, but the one in your own user account is the one we’re interested in. The LaunchAgents folder is responsible for ensuring certain things launch, as the name implies, every time you login. This is achieved by executing files called “property lists” or plist for short.

Property lists are really useful, and are meant as an aid so that you don’t have to keep starting up lots of processes manually every time you log into your account. They can also be used to make sure that a process stays alive all the time that you’re logged in. Great for things that you want to happen, but bad if you have got some adware or malware that you’re trying to get rid of.

If MyCouponsmart is installed on your Mac, you should find it has installed a property list in the LaunchAgents folder to ensure that it’s always running. Before getting rid of this, let’s just take a look at it. You don’t need to open it in an editor, just select the file by clicking it once and then pressing the spacebar to allow QuickView to show you the contents.

adware plist in LaunchAgents folder

Notice that first ProgramArgument? It points to a folder within your /Applications folder, also named MyCouponsmart, and then to something else with the same name inside that folder, too. Let’s go take a look at what they are.

adware bash script in Applications folder

If you want to play along, open the Terminal, type the word file then drag the MyCouponsmart executable into the Terminal window. Press ‘return’.

The file command reveals that the MyCouponsmart file is actually a bash script, and if we take a look at its contents with the cat command, you can see that the script is itself meant to launch another executable called mmLaunchMe located in the hidden /tmp/ folder. Let’s see if this executable has a valid code signature.

codesign -d -v /tmp/mmLaunchMe

image of examining mycouponsmart files

No, indeed it doesn’t, but as I’ve written about before, that won’t stop the code from running, regardless of what Gatekeeper settings you use. The purpose of this executable is to run every time you login, and download more software that you didn’t specifically ask for in the background. It’ll keep on doing this every time you login until you remove it. Of course, by then you’ll have lots of unwanted programs to remove, too.

How do I remove MyCouponsmart?

The main thing to do to remove MyCouponsmart is to delete the property list and restart your computer. After that, you’ll need to search and find all the components it’s installed. If you like playing around in the Terminal, I have a post here on how to do that.

Alternatively, you can use the shareware app I created, DetectX Swift, which will remove the property list and all the other components for you.

remove my coupon smart with detectx swit

Notice from the Activity Log that DetectX also automatically kills background processes belonging to the adware as well as removing the files. Nevertheless, you should always restart your Mac after removing these kinds of files to ensure you have purged everything from running memory.

You can use DetectX Swift to remove MyCouponsmart and similar adware without registering or paying any fee. In fact, I encourage you NOT to register DetectX Swift until after you’ve used the app a few times and feel you want to support the continued existence of shareware apps like this. Payment is not at all required: nobody should have to pay just to remove junkware from their Mac!

If you have any questions about removing MyCouponsmart or about using DetectX Swift, feel free to share them in the comments below.



Picture Credits: Anaya Katlego

adware extensions erode trust in Apple, Google app stores

image of redirect to pup

Browser extensions are a staple of almost every user’s set up. Even in managed environments, users are often able to install extensions or ‘Add Ons’ without authorisation when these are sourced from trusted sources like Apple’s Safari Extensions Gallery and Google’s Chrome store. Of course, there’s nothing new about attackers exploiting the browser extension as a means to gaining a foothold in a target environment. The problem has been around for years: what is surprising is just how difficult it is to contain the problem. In this post, I take a look at the risks involved with what appears to be a harmless extension available for both Safari and Chrome. As we’ll find out, not everything appears as it seems.

Continue reading…


Lazarus APT targets Mac users

image of lazarus hacker group

Last month, researchers at Kaspersky reported on a Lazarus APT campaign targeting both macOS and Windows users involved in the financial sector, particularly those using cryptocurrency exchanges. The Lazarus group, also known as Hidden Cobra, have been operating since at least 2009 and were most notoriously blamed for the 2014 hack on Sony.

Continue reading…


let’s bury the myth of the safe Mac

image for do macs get malware

Do Macs get malware? Can my Mac get infected by a virus? Do I need AV software for my Mac? These are questions I hear a lot, but the answers that come from many so-called Apple Mac gurus are often wrong or misleading.

In this post, we’ll take a look at some of the reasons why people think Macs are safe from malware and the confusions that are often bandied around concerning “AV” (“anti virus software”), “viruses” and genuine malware. Then we’ll look at the actual security situation on macOS and make some suggestions as to how you can stay safe without turning yourself into a paranoid security conspiracist or downloading useless software that just eats up your system resources while providing no real protection.

“It’s All Security Theatre” theatrics

There’s an unfortunate and dangerous misconception perpetrated by certain people in the macOS community. These people variously claim that there is no malware threat to Macs, or if there is then Macs are immune from it, and no matter what the case, Macs are inherently safer than other kinds of computer, specifically Windows computers.

The purveyors of such arguments typically make a big deal of trying to undermine any argument that security is an issue on macOS by claiming that malware on Macs is all a myth made up by AV vendors to drum up business for their own products. In many Mac user forums, people worried about hacking and malware are often treated to dismissive replies of this sort:

“you are at much greater risk from a concussion due to a fish falling from the sky. The Mac AV industry and security researchers have worked very hard to make you believe this is something to be afraid of.”

The claim that emanates from such people often begins with “there are no known viruses for macOS” and, therefore, you don’t need anti-virus software. This is a laughable confusion of terminology.

image of do Macs get malware

AV software is inappropriately named. There actually aren’t any known viruses on macOS, it’s true (these days, there are very few for Windows either and most AV software isn’t primarily looking for them). That’s because viruses are a specific kind of threat that went out of fashion long ago. Viruses were the product of vandals; the modern security threats facing macOS users are the products of profiteers. It’s a different ball game.

These days, criminals are more interested in pushing macOS adware, backdoors, keyloggers, RATS, trojans and spyware. Ransomware has also been known on the platform, though thankfully to date that’s an isolated incident.

The conspiracy theorists like to point out that security vendors have a vested interest in making people fearful. It’s rather like saying insurance companies or law enforcement have an interest in higher crime rates. I’m all for healthy cynicism. The reality is that there are, indeed, commercial interests involved in fighting malware just as there are in fighting other kinds of crime. And where there’s commerce, you’ll also find cheats and unscrupulous dealers. There are plenty of dodgy AV products around; some are even on the Apple App Store. Some of those proclaiming that the security industry is all fraud are pushing their own software as an alternative. Unscrupulous, indeed.

Be wary of any software that offers to “find” threats but then insists you pay up in order to remove them or which tries to lock you in after minimal use where you cannot fully determine the value of the offering.

image of mackeeper fake search

However, unlike the one shown above and others like it, there are genuine security products out there developed by genuinely-good people serving the community.

But the real point is that the existence of commercial interests in the anti-malware industry is, on its own, no more an indicator of duplicity than it is in any other industry. While amplification of threat intelligence through news stories, tweets and other social media serves the security industry just as amplification of relevant issues serves any business sector, to claim that all vendors are unscrupulous or that the threat is entirely fictional is disingenuous and worse, it’s dangerous.

As we’ll see below, the threats are real, but the conspiracy theorists threaten to lead macOS users into a false sense of security.

Burying the Myth of the Safe Mac

It’s not just the conspiracy theorists you have to watch out for. It’s also the “wisdom of the wise”. Far and wide, you’ll hear Mac gurus arguing from their own personal experience that, since they’ve never encountered macOS malware and they’ve been using the platform for x, y, z amount of years, there are, consequently, no malware threats to macOS and that it’s inherently safer than other platforms.

The logical fallacy in that should be clear. Arguing from a sample of one to a conclusion for all is just bad thinking. It also should perhaps come as no surprise if a “power user” hasn’t come across threats to their own Mac. They typically have limited and specialised interests that don’t take them to many of the far corners of the internet. Power users also tend to write scripts or even their own software to do things on their Mac, whereas other users would instead go looking for a tool to download from adware-infested mass distribution sites, torrent sites and who-knows-where, with all the risks that that involves.

When the self-professed gurus tell you they have never encountered a security issue on a Mac, they aren’t testifying to the safety of the platform; they are in fact revealing only that they know nothing about macOS security.

Will Gatekeeper Protect You From Malware?

Some people are more realistic and acknowledge the existence of the threat, just as Apple themselves have done by building anti-malware protections into macOS itself, namely, Gatekeeper, XProtect and MRT (Malware Removal Tool).

Because Apple have taken these measures and have been pretty vocal in their marketing about it, too, many think that Apple’s built-in security technologies will keep them safe. Here’s a typical example of this kind of thinking, where a forum poster suggests Apple may not be sharing information about malware threats because they can just kill them by revoking the malware developer’s code signature.

image of post about apple gatekeeper

Of course, there is no such setting as “Run only signed apps”, but seasoned Mac users would understand that the poster is referring to Gatekeeper, which is the first check the system makes on application code signatures.

Unfortunately, the poster is just flat-out wrong. Even when set to App-Store only, it’s a simple matter for even a standard user to run apps with invalid signatures or no codesigning at all. Both Gatekeeper and XProtect are easily bypassed. Not only can standard users override Gatekeeper’s “App Store only” settings, so can other processes. None of this needs admin privileges. As for Apple’s Malware Removal Tool, it is useful to the extent of its signature database, but it has the major limitation that it only runs when you reboot your Mac.

Malware Campaigns That Target macOS Users

A typical day for me hunting macOS threats on VirusTotal looks something like this, with several hundred new samples to inspect:

image of a threat found on virus total

So, yes, macOS malware is a thing and it’s out there. From nation state actors to sneaky hackers on Discord, if you’re using a Mac to interact widely with other people, visit websites, read email – in other words, doing the things that make your Mac useful – then there is a non-negligible chance of you encountering someone trying to infect your Mac.

In 2018 alone, we saw the emergence of malware families such as OSX.MaMi, CrossRAT, OSX.AppleJeus, WindTail, OSX.Dummy, CoinTicker, OSX.DarthMiner and OSX.LamePyre. On top of that, we’ve seen the appearance of a number of adware installers acting as trojans for cryptominers, such as PPMiner, CreativeUpdate and SearchPageInstaller. Old favourites like OSX.Fruitfly remain viable threats that can be repurposed by other actors as neither XProtect nor Gatekeeper is equipped to tackle script-based and fileless attacks.

Adware and PPI (pay-per-install) PUPs (potentially unwanted programs) like MacKeeper and Advanced Mac Cleaner, MyShopcoupon and chill tab are rampant. Adware in general is an increasing concern as we see adware developers expand their range of techniques and begin to cross the line into malware-like behaviour. Browser extensions are still a widely unappreciated threat, built-in browser anti-phishing protections are easily defeated, and if you haven’t had a phishing email in your Inbox then you are likely one of an increasingly diminishing global minority.

Finally, let’s note that for criminal types, it’s never been easier to get into the macOS malware business with the proliferation of dedicated exploit kits like empyre, EvilOSX, Pupy, Bella, EggShell and others.

How To Stay Safe on macOS

The evidence provided above is conclusive: the threats are real, so don’t let anyone try to kid you otherwise.

That said, the most widespread, “in the wild” problems affecting Macs today come from adware and PUPs. It might not be the end-of-the-world if your Mac gets infected with some nuisance adware and scam virus alerts keep popping up in your browser, but neither is it a particularly pleasant experience that you should have to put up with.

Fortunately, dealing with them is fairly straightforward, so let common-sense prevail. Most home users don’t need the expense or resource-impact of a full-on AV Suite. Reboot your Mac often to take advantage of what protection the built-in MRT tool offers, and use a lightweight, troubleshooting tool like my DetectX Swift to help diagnose and remove problems if your Mac starts behaving oddly.

image of detectx swift search results

While the technically-proficient may be able to deal with a lot of adware from the Terminal, DetectX is light enough to be run on a regular or scheduled basis (like after you install any new software) and can look for and remove adware, malware, keyloggers and more.

You can use DetectX Swift indefinitely and without paying a cent. It won’t burden your finances with a monthly subscription bill or demand that you pay money to remove suspicious or unwanted files, or insist that you pay up after a few uses. While there is an optional registration for home use which also provides a few bonus features, it’s not necessary to register in order to use the app’s core functionality. You can even script it with AppleScript and enjoy almost all the troubleshooting functions it offers as an unregistered, unpaid user. I also offer free, personal triage to both registered and unregistered users if you have an issue that DetectX does not resolve.

If you have a fleet of Macs in an organisational setting you might want to consider the low-cost, DetectX Swift Management license in order to access the command line search tool and integrate with platforms like Jamf or Munki. For more in-depth coverage and cross-platform support, enterprises should look at next-gen AV software that uses behavioural AI like SentinelOne.



Picture Credit: Mikayla Mallek

how to reverse malware on macOS

Resources for learning malware analysis and reverse engineering abound for the Windows platform and PE files, but by comparison there’s very little literature or tutorials for those who want to learn specifically about how to reverse macOS malware and macOS malware analysis techniques.

In this series of posts, you’ll take a sample file and use native tools and techniques to understand what a file does and to build a list of IoCs (Indicators of Compromise) that can be used in detection.

image of reverse engineering malware on macos

As there’s a lot of ground to cover, the tutorial is split over several parts. In Part 1, you’ll learn how to set up a safe environment to test malware on macOS. You’ll install all the tools you need (bonus: doesn’t cost a cent!) and learn where you can source samples of macOS malware from. You’ll examine an application bundle and its contents to understand how it works and find an interesting encrypted text file. In Part 2, you’ll learn the fundamentals of static analysis of Mach-O binaries, the native executable file type for macOS. In Part 3, you’ll use dynamic analysis techniques to execute a malware file in a controlled manner and read code from memory.

If you have ever wanted to learn how to reverse malware on macOS, this is the place to start! Continue reading…


Mojave: not authorized to send Apple events

If you’re suffering from error messages like the one above after upgrading to Mojave, welcome to macOS’s new “User Data Protections”. In this post we’ll explain what they are and how to deal with them.

That error’s produced when the app your script is targeting (in this example, System Events) has been denied access to one of the areas now protected in Mojave.

Here’s the list of places which are no longer accessible programmatically without user approval on 10.14:

If the app you’re targeting in your script – or the script runner itself – is trying to access any of those 12 locations, you’ll likely either get the error shown at the top of this post, or some other failure. 

The official way of dealing with this is to add the application to System Preferences’ new ‘Full Disk Access’ section in the Privacy pane:

At least that’s the theory, but you might find that you’ve tried that and things are still not working. If that happens, you can “start over from scratch” by resetting the access permissions to default. 

In Terminal, try 

tccutil reset AppleEvents; tccutil reset SystemPolicyAllFiles

After you’ve done that, the next time you run that script you should get an authorization dialog like this: 

Alternatively, just go right ahead and add the app with the ‘+’ button in System Preferences.

Enjoy the resumption of normal service 🙂


hello, applescript 3: (don’t?) tell me to run

Continuing where we left off at the end of User In, User Out, let’s build on our knowledge of getting user input and using conditionals.


Script 7
In this script, we’re going to query the user for some information, and if that information meets a certain test, we’ll give the user one answer, if it doesn’t we’ll give them another. Kind of like a mini-quiz game program. There’s lots of new stuff in this script, but don’t be put off. Just bang it out on the keyboad, fix any typos if it won’t compile, and run it. Run it at least three times choosing a different button each time. We’ll go through it line by line after you’ve had a play around with it.





Line 1 assigns a string literal (the lovely “Loser”) to a variable, theReply. We’re doing two things here. We’re first declaring a variable that we’ll want to use later in the script, and we’re also initialising it with a default value. “Loser” is one of two possible values we’ll want this variable to have later, so we’ll set this as the default now, which means the variable will always have this value when we use it unless we change it later in the script.

Most of Line 2 should be familiar to you now, except that we’ve added a third button and a default value for the answer. We’ve also added a default button, in this case 3. To understand what the default button parameter does run the script with value 1, and then again with value 2.

As you will notice, the number refers to one of the buttons defined in the buttons list, where 1 is the first item in the list and the left most button, and 3 is the last item in the list and the right most button. The parameter determines which button has focus (and therefore responds to the return key on the keyboard).


If you’ve already tried experimenting with 4 buttons, you’ll see that the compiler complains that a maximum of 3 buttons is allowed. That’s not strictly true, but we’ll save that trick for later in the series.

Note: Lists in AppleScript, unlike most other modern programming languages, are not zero-indexed. The first item is item 1, not item 0 as it would be in Python, C, Swift and so on.

If you prefer you can also refer to buttons by their name instead of their index. This helps improve readability of your code and makes it clearer which button was intended as the default. To refer to the button by name, you would write the parameter like this:

default button "Sure?"

Line 3 should be familiar to you, but refer back to Script 6 in the previous post if you need a reminder.

Line 4 begins an if statement block that contains another if statement block (again, see Script 6), but there’s also something new here: the else condition. This says that if our condition in Line 4 isn’t met, do whatever’s in the else block starting at Line 10.

If the condition in Line 4 is met, however, then Line 6 offers a further condition: if the user typed in “Phil”, then Line 7 says change the value of the variable theReply from “Loser” to “Winner”. Note, particularly, that if this condition is not met, then the value of theReply will be “Loser” when it’s called later in the script.

Line 8 ends the inner if statement block.

Line 9 now says: display the dialog to the user, showing them the value of whatever theReply is currently set to (either “Winner” or the default “Loser”). Note that the same value is used to set the title.

Line 10 starts the else block. This will be triggered if the user doesn’t choose either “Cancel” – which would end the script – or “Sure?” – which would trigger the first condition – when Line 2 is executed.

We don’t need to put in a specific test for “Cancel” because “Cancel” will automatically end the script with error -128. However, as we’ll see later in the series, sometimes it can be useful to catch “Cancel” in the if block too, in order to execute certain commands before the script quits.

Line 11 may look a bit mysterious; this is your first introduction to AppleScript’s most pervasive control statement. tell is how you send a command to a particular object in AppleScript. If you’ve ever done any Object-oriented programming, another way of expressing the same idea is to say tell allows you to target a message toward an object. In this case the object is me — a built-in AppleScript keyword that refers to the script itself. So,

tell me to run

says “send the run message to the script”.

There’s an easy (and inaccurate) way to understand what that means, and a hard (and accurate) way. For now, we’re going to go easy so that the learning curve doesn’t get too steep. In this context, we will say that run means “go back to Line 1 and begin execution of the script again”.

Every time you choose “Try Again”, the script goes back to Line 1 and repeats itself until you choose one of the other answers.


Where we are: so far!
In this post, we’ve been introduced to AppleScript’s list class, consolidated our knowledge of display dialogs and if statements, and had our first taste of tell, me, and run. These concepts will require more elucidation and, most importantly, more practice, all of which are coming up!

In the next post hello applescript 4: shelling out, we’ll work with these concepts some more and build on them to produce our first practical scripts. Be sure to follow Applehelpwriter to be notified when the post is published.

See you there! 🙂




For extra credit:

This week’s extras
1. Modify Script 7’s inner if statement so that if the text returned contains your name, theReply is “Winner”; if the text contains “Phil”, theReply is set to “Runner Up”. Any other name should produce the default reply “Loser”.

There are in fact two ways to solve this challenge, see if you can produce both. For help, look up else if in the Control Statements Reference section of the AppleScript documentation.



Solutions from last time
1. Use the hidden answer parameter:





2. In the second exercise, we posed a number of questions. The easiest way to find out about the parameters for a command is to use Script Debugger’s Dictionary viewer, which you can access by clicking on the Window menu (not, confusingly, the Dictionary menu!) and choosing ‘Dictionary’.


Also, don’t forget to use the AppleScript documentation, which I’ve linked to multiple times in this and earlier posts. It’s a great source of information, hampered somewhat by the lack of an effective search feature on Apple’s site. An older, pdf version of the doc which you can search can be downloaded by clicking this link, and is also available from here. Bear in mind, though, that Apple’s online docs contain some information that the older pdf doesn’t.

We’ll leave the other questions open for now, as they’ll be coming up in later posts!





hello, applescript 2: user in, user out

If you’re ready to learn AppleScript, this is the place to start! If you’re not sure yet whether AppleScript is for you, take a look at the intro to this series, What’s the Use. For those of you that are ready, let’s fire up Script Debugger and write our first script!


Script 1
OK, you want ‘hello, world’? Of course, you do!

Here it is, with a difference:





Type it in to the editor’s window, then run the script by clicking the Run button or hitting “Command-R” on the keyboard.




Wow. No “print” command for one, and an actual user interface. Cool!

If you don’t see a notification in the top right of your screen, you may need to adjust your Notification preferences.

What happens if you leave off the last quotation mark?

Try it and see:




This is called a compile time error, one of three kinds we’ll learn about (the others are run time and logic errors). When you run a script, the AppleScript compiler first checks it for syntax errors. If all is well, it turns your plain text into “pretty print” (we’ll talk about what the syntax colouring means later in the series); if not, your text isn’t compiled and you get an error message.

You can get a compiler check anytime without running the script by clicking either the button or using “Command-K” on the keyboard.

You’ll notice that when you have a compile time error in Script Debugger, you get a message and the error number in the bottom left corner (you won’t see the error number if you’re using Apple’s Script Editor). These can be useful, so much so that we’ll write a little script ourselves to tell us more about the error based on the error number we get in hello, applescript 4: shelling out.

For now, let’s take a look at the message.

“Expected string but found end of script.”

It may seem rather cryptic at first, but it can be translated simply enough. A string in AppleScript (and most other programming languages), is text placed between a pair of quotation marks. Anything between quotes will be treated as just a piece of ordinary text and not as part of the programming language. display notification isn’t a string in our script: it’s part of the programming language – specifically, a command to do something. “hello, world”, on the other hand, is a string: it’s just the ordinary text we want to display. The compiler says it “expected a string” because it found the first quote mark at the beginning of “hello, indicating the start of a string. It then went looking for the second one to mark the end of the string, but instead found…yes, you guessed it: the end of the script!


Script 2
Replace the missing quotation mark. We’ll come back to error messages shortly, but for now, let’s add our own title to the notification rather than having the default one:




Make sure those quotation marks are balanced!




Looking good!


Script 3
Notifications are useful when all we want to do is pass a simple message, but if you need users to make a choice or you need to provide a longer message, we should use a dialog.

Type in the script as you see it on the left in the image below.




Run it, and click the “OK” button when the dialog appears. Now look at the Results pane (right-hand panel in Script Debugger; bottom Accessory view in Script Editor).

That looks interesting! Let’s explore some more.


Script 4
Let’s add some bells and whistles:




Run the script.




Click either one of the buttons to end the script. Again, remove the quote mark after “world”, but this time don’t try to run the script. Just try to compile it. Remember, you can do that either by clicking the button in the toolbar or “Command-K” on the keyboard.

Notice this time we get a different error message and a different number, despite the fact that we seem to have errorred in exactly the same way and in exactly the same place as before:




Or did we? Look at it from the compiler’s point of view. Just as before, the compiler finds the first quote mark and continues looking. But this time it does find the second one! Only it’s not where it’s meant to be. Because we left off the quote mark after “world”, the compiler assumes that the quote mark that prefixes “Message is the closing quote mark for the opening one:




As a result, the term Message looks to the compiler like its supposed to be part of the programming language, as it follows the string “hello world with title ”. That sure is a valid string (you can put any text you like in your string, it doesn’t have to make sense), but what follows it is not a valid part of the programming language. You can learn more about identifiers here, but for now, just note that this error message has the form “this can’t go after that”, and is another clue that our quote marks are unbalanced.

What about the third quote mark? The compiler never sees it. The compiler reads from left to right, so after pairing the first two quote marks it throws the error and stops trying to read any further. If there are further errors in our script, we’ll never know till we fix (all) the preceding ones.

After you dismiss the error alert, the compiler is kind enough to highlight the this (“Message”) that can’t go after the that (“"“) in your script.

Errors -2740 and -2741 are common enough that whenever you see them, you now know what to check first: are my quotation marks balanced?

Let’s get back to our display dialog command. Are you wondering what happens if you use another number instead of 2 after with icon? I hope so!

Replace the missing quotation mark, and experiment by changing the number after with icon for all three values from 0 to 2.

Normally, you’ll use with icon 1, which will insert the icon of the executing program. In this case, that’s the icon for Script Debugger, but as you go through this series you’ll be learning how to execute your scripts in other ways, and it’s useful to have the icon of the executing program visible in the dialog box so that you know exactly where it’s coming from.

Our dialog box has some unnecessary cruft. We have an “OK” button and a “Cancel” button, but they appear to do the same thing; that is, they halt the script. But look a bit closer at the editor. Run the script again, twice, choosing the “Cancel” button first, and then the “OK” button on the second run.

When you choose “Cancel” there is no result, but there is an error message in the Events pane, specifically, error -128.




Errors, error messages and error numbers are powerful friends. We’ll see how we can harness errors like -128 later in the series.

When you run the script again and choose “OK”, however, there is a result. There are many result types, but in this case you get what is known as a record (similar to a Dictionary or key/value pair in other languages) in the Results view:

{button returned:"OK"}

The record contains a label (in this case, button returned, and a value (here, "OK"). This is important, as we’ll see in the following scripts.


Script 5
What if we want to get more than just an acknowledgement, but need some input from the user? Here’s one way:




Run the script, type in an answer, and hit “OK”. Take a look at the result:

{button returned:"OK", text returned:"Phil"}

It’s a record again, with the added pair “text returned” and the text that the user typed.

The default answer parameter is an empty string. What happens if you put some text between the quote marks and run the code?


Script 6
Let’s build on Script 5 and capture the answer that the user provides:




This script has a lot of new stuff going on. Let’s take it from Line 2 (refer back to Script 5 for line 1):


Line 2
This captures the result of the dialog in a variable called dialogAnswer. The result of the dialog isn’t the name you typed in, but the record of two labels with two values. In other words, the value of dialogAnswer is:

{button returned: "OK", text returned: "Phil"}

We could have called the variable (almost) anything we liked. I just chose dialogAnswer because it’s descriptive.

Descriptive names are useful because when I read back my script at some point in the future, it’ll be immediately obvious what this variable represents. However, I could have called it alpha, or just d or almost anything else. There are some reserved words in AppleScript that you can’t use, and you also can’t start variable names with a number or use certain special characters in them, as noted here.

Most commonly, we use the set command to assign values to variables. In many other programming languages, they use the = sign, like this:

dialogAnswer = result

You can’t do this in AppleScript (or rather you can, but it means something else, not variable assignment), so if you’ve come to AppleScript with a background in another language, you’ll need to make the mental adjustment.

What about result though? Where did that come from? This is a built-in property, filled with the value of the last command to be executed.

Take a moment to consider that. It means that the result property changes on (almost) every line of your script.

Before we continue working through the rest of Script 6, let’s take a closer look at the result property. Type this in, then compile and run it:




Notice that in the Events pane, result changes from 2, to 3 and finally (in the Results pane) to 6.




AppleScript can use the usual programming conventions for mathematical operators (+, -, /, *. For x % y, use x mod y). That also includes the = sign, where it means “is equivalent to” (aka “==” in many other programming languages) and not, as we mentioned above, “assign to”.

In this little script, we also learned how to use the log command to print the value of a variable to the Events pane. In Script Editor, you’ll need to do that a lot if you want to see the values of your variables at different times in your script. In Script Debugger, however, it’s rarely necessary as you can see the values in the Variables inspector view.

To verify this, try removing the two log statements and running the script again. The log statements no longer appear in the Events pane, but Script Debugger captures them anyway in the Variables inspector view.


Line 3
Line 3 of Script 6 is an if statement, a kind of control flow statement. The clause, in this case, takes the form of a block. That means it evaluates a condition on one line, executes any commands if the condition is met on subsequent lines (Line 4) and then provides an end statement (Line 5) to signal the end of the block.

The conditional here first examines the button returned property of the result, which, remember, we’ve captured in the dialogAnswer variable.

After the conditional has been evaluated and any commands executed if the condition was satisfied, the rest of the script continues to execute as normal. In Script 6 there were no more commands after the block, so the script ends.


Line 4
In Line 4 of Script 6, if the user clicked “OK”, we set a new variable, theName, and assign it the value of the text returned property of the dialogAnswer record. Because we ended the block and the script on the next line, we never actually got to use this new variable, but typically the point of doing this would be so that we can use that value somewhere else in our script.


Where we are: so far!
Woah! We’ve done a lot in this post! We’ve seen how to get data in to our scripts from users and how to get data out, through dialogs, notifications and the Events and Results panes. We’ve had a first go at writing a conditional, logging messages, and viewing variable values. We’ve also been introduced to the compiler’s error messages and AppleScript’s record class.

If it’s all a bit of a blur, don’t worry. We’ll be practicing all of this, and expanding our skills some more, in the next post in this series, hello, applescript 3: (don’t?) tell me to run!. Be sure to follow Applehelpwriter to be notified when a new post is published.

See you there! 🙂





For extra credit:
1. Try to modify Script 6 so that when you run it and type in your name, it looks exactly like this.




You’ll need to consult the docs for display dialog, so try to find and explore Script Debugger’s Dictionary viewer in order to do that.

2. Go back to Script 4. What happens if you set with icon to 3?
This is an example of a run time or ‘execution’ error. The script will compile fine, because the parameter, or value, for with icon only has to be a number in order to compile. AppleScript tells you ‘a resource wasn’t found’ because, unlike ‘icon 0, ‘icon 1’ and ‘icon 2’, there’s no such thing as ‘icon 3’.

That raises a number of questions: how can we tell what kind of parameter an argument or command takes? Why are there only three icon resources and where are they declared? How can I add other icons if I want to? And last, but most importantly, what else do we need to know about run time errors? All this, and much, much more, will be covered in the hello, applescript series. Stay tuned!