TweetFollow Us on Twitter

Mac in the Shell: Automation Potpourri

Volume Number: 23 (2007)
Issue Number: 06
Column Tag: Mac in the Shell

Automation Potpourri

Shell and GUI scripting come together

by Edward Marczak

Introduction

Last month, I gave an overview of some commands that I felt just didn't have the coverage and documentation that they deserved. The theme this month is commands that enable us to tie our shell scripts into the GUI. While I'm an advocate for good ole bash scripting, there are times when it's easier or better for some reason to tie in a GUI app. Think about scripting Safari, Address Book or Excel using familiar utilities in the shell. What about incorporating an AppleScript into a workflow with data piping in and out of it? If that sounds like a panacea, read on!

AppleScript

Under OS X, AppleScript is the clear reach-into-just-about-anything scripting technology. Why choose bash scripting over AppleScript? Let me enumerate some ways:

Portability.

Existing stock snippets.

Speed.

Familiarity.

Ability to do things that AppleScript alone can't do.

Since the addition of 'do shell script' to AppleScript, there's little we can't coerce it into doing. This allows us to call a shell script from within AppleScript and return the results. What a powerful combination. That's great when the logic and script itself lie mainly in AppleScript. However, what if the situation were reversed? What if you have a lengthy shell script that needs to utilize an AppleScript? Enter 'osascript'.

osascript allows us to execute AppleScript commands and scripts from a standard shell. In the it's-getting-better-all-the-time category, as of 10.4 ("Tiger"), you can pass arguments into osascript, and AppleScript can pick them up in the 'argv' variable. It can run simple AppleScript commands all in one shot, or, it can run a script file. Let's see an example:

osascript -e "tell application \"Safari\" to launch"

That's about as simple as it gets. Standard shell conventions apply, so make sure you escape quotes and other special characters. The "-e" flag is used to denote a 'command,' or line in the script. Scripts that need multiple lines need multiple "-e" flags. For example, look at this command:

osascript -e 'tell application "Finder"' -e 'make new Finder window to folder "Applications" of startup disk' -e 'end tell'

Three lines of AppleScript, three "-e" switches. Note the use of single quotes here to avoid the pain of escaping double quotes. Naturally, you probably want to put lengthy or complex scripts into their own file. So, the previous example could have been its own file:

new_app_win.scpt
tell application "Finder"
   make new Finder window to folder "Applications" of startup disk
end tell

This could then be invoked as "osascript new_win_app.scpt". Pretty handy. (Of course, this contrived example could be replicated easily in the shell alone as "open /Applications").

The Real Power

So, rather than come up with anything too contrived, let's explore where you may really use this. Let's take a look at a script that, in part, I really use.

Once upon a time, I had a script that mashed and mangled a bunch of data nightly. It would get this data from various data sources: MySQL, text files and the web. For the web sources, I simply used curl to fetch the data I needed as CSV files. Well, one day, my script stopped working. Why? Security. The web site in question required a certain login sequence, and tokens were generated for each form and page load so they couldn't be forged. Consequently, I needed a 'real' browser to do this part. Safari and AppleScript to the rescue. I was able to keep my shell script in place and largely untouched. I did need to swap out the curl calls, of course, and replace them with osascript auto_web_dl.scpt. The AppleScript file scripts Safari to load pages, click links and save the resulting file. Let's dissect:

auto_web_dl.scpt

on run argv
   tell application "Safari"
      activate
      -- Initial load
      set URL of document 1 to "http://some.example.com/page/"
      repeat until do JavaScript "document.readyState" in document 1 is "complete"
      end repeat
      delay 5
      
      -- click the link
      set URL of document 1 to do JavaScript "documents.links[3].href" in document 1
      repeat until do JavaScript "document.readyState" in document 1 is "complete"
      end repeat
      delay 5
      
      -- load the reports verification page
      set URL of document 1 to "https://setup.example.com/¬
accounting/check? done=http%3a//some.example.com%2Faccouting%2Freports" repeat until do JavaScript "document.readyState" in document 1 is "complete" end repeat delay 5 -- fill in the values do JavaScript "document.getElementById('realm').value = 'ap'" in document 1 do JavaScript "document.getElementById('history').value = '1'" in document 1 do JavaScript "document.settings_form.submit()" in document 1 repeat until do JavaScript "document.readyState" in document 1 is "complete" end repeat delay 5 -- get the reports page set URL of document 1 to "http://some.example.com/accounting/¬
cur_report?export=true&level=sub" repeat until do JavaScript "document.readyState" ¬
in document 1 is "complete" end repeat delay 10 -- save the contents set theSaveName to "acct_nightly.csv" set theSavePath to (path to desktop folder as string) & theSaveName tell application "Safari" save document 1 in file theSavePath end tell tell application "Finder" if file (theSavePath & ".download") exists then set name of file (theSavePath & ".download") to theSaveName end if end tell end tell end run

(A big thank you to Ben Waldie from automatedworkflows.com for teaching me how to get Safari to save a plain text document! Not being an AppleScript person by nature, I just couldn't nail it down).

So, yes, this took a little knowledge of JavaScript and Document Object Model. Not terribly esoteric, but if you're solely a bash scripting person, this may be a bit foreign. Now, my shell script remained in bash, and runs as a nightly cron job that delivered reports to company executives. The abridged version is now this:

#!/bin/bash
# Grab initial MySQL data
mysqldump -u db_user...> /data/table1.csv
# Grab web data
curl —LO http://financialinfo.example.com/stocks.php?id=2345
# Grab accounting data
osascript auto_web_dl.scpt
# Process results
/usr/local/bin/data_process /data

Further Interaction

More than just being able to call AppleScript from the shell, there are several ways to pass variables between the two environments. The first is a natural extension of what you know from bash. Simply put the bash variable on the command line:

$ osascript -e 'tell application "Finder"'¬ 
-e "display dialog \"Hello, $USER\"" -e 'end tell'

This will display a dialog box in the Finder containing the name of the currently logged-in shell user. Notice also, that when this is run, osascript returns values to the shell. Again, of course, you can use or discard these values as the situation dictates. Note that this is a valid way to pass data out of AppleScript and back into the shell.

Look at the possibilities this opens up! Take, for example, the following script:

#!/bin/sh
for user in $(dscl /LDAPv3/127.0.0.1 -list /Users)
do
        ma=$(dscl /LDAPv3/127.0.0.1 -read /Users/$user mail)
        osascript -e "tell application \"System Report\" process $ma"
done

Here, we use bash and dscl to pull all users from Open Directory and then feed each of those into the fictitious application "System Report".

Another way to pass data between the two environments is via environment variables. AppleScript will happily reach out and grab environment variables from a shell using the system attribute variable. Let's say each user on the system has environment variable defined for their favorite color called, "my_color ". Without passing it in as an argument, AppleScript can access it like this:

set favorite_color to system attribute "my_color"

You can then go on and have AppleScript make decisions based on your new variable.

Finally, you can pass and values into the AppleScript as arguments. Given the following AppleScript:

on run argv
   tell application "System Events"
      repeat with currentArg in (every item of argv)
         display dialog currentArg
      end repeat
   end tell
end run

It could be called like this:

osascript asarg.scpt mike bill joe

This will cause three dialog boxes to appear, each containing one of the arguments passed in.

The trick here is wrapping everything in the "on run argv" block. Since argv is an AppleScript list, you can access any element directly. For example, argument one is simply, "item 1 of argv".

In Conclusion

I hope this short, but important topic, stirs some ideas in your head. These techniques truly make the scripting environment boundless. While there are many, many cases where you can script a workflow entirely in bash, or entirely in AppleScript, they are also many reasons to integrate the two. I talk consistently about remote management and troubleshooting of Macintosh systems. This is yet another great weapon in your arsenal. With only command line access, you can now launch applications, interact with them, and the user sitting at the console.

Using osascript also allows AppleScript into places that it is usually not allowed in. Think about a user interacting with a web page, and one of their actions runs an AppleScript. You can also use osascript to interact with users at important times. You can display a dialog box prior to running a CPU intensive cron job. This trick also comes in handy to alert users of actions being taken during login hooks.

One thing to note, though: while the data coming out of osascript is on stout, osascript has no concept of stdin. So, you need to use one of the techniques covered here to get data into an AppleScript. You just can't pipe your data in. (OK, in all fairness, you could get data into an AppleScript by reading a file or through sockets, etc. — just not via stdin!).

Don't forget: interaction with osascript isn't just limited to bash and its constructs. Take a look at this great example from Apple's own, "AppleScript Overview":

osascript -e 'tell app "Address Book" to get the name¬ 
of every person' | perl -pe 's/, ¬
/\n/g'| sort | uniq —d

This one liner will output duplicate entries from your address book. While I'm sure this could have been scripted entirely in AppleScript, it's unlikely that it would have been as concise or elegant as this one-liner.

The point is simple: mix and match as needed to solve the problem at hand. You have many varied tools at your disposal, each with particular strengths, advantages and weaknesses.

Media of the month: It's Johnny Cash month! If you've never listened to, "At Folsom Prison", do yourself a favor and experience it. If you know virtually nothing of the man, go rent "Walk the Line".


See you next month, post WWDC!

Ed Marczak owns and operates Radiotope, a technology consultancy specializing in automating business processes and enabling communications between employees and clients. Communicate at http://www.radiotope.com.

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Fresh From the Land Down Under – The Tou...
After a two week hiatus, we are back with another episode of The TouchArcade Show. Eli is fresh off his trip to Australia, which according to him is very similar to America but more upside down. Also kangaroos all over. Other topics this week... | Read more »
TouchArcade Game of the Week: ‘Dungeon T...
I’m a little conflicted on this week’s pick. Pretty much everyone knows the legend of Dungeon Raid, the match-3 RPG hybrid that took the world by storm way back in 2011. Everyone at the time was obsessed with it, but for whatever reason the... | Read more »
SwitchArcade Round-Up: Reviews Featuring...
Hello gentle readers, and welcome to the SwitchArcade Round-Up for July 19th, 2024. In today’s article, we finish up the week with the unusual appearance of a review. I’ve spent my time with Hot Lap Racing, and I’m ready to give my verdict. After... | Read more »
Draknek Interview: Alan Hazelden on Thin...
Ever since I played my first release from Draknek & Friends years ago, I knew I wanted to sit down with Alan Hazelden and chat about the team, puzzle games, and much more. | Read more »
The Latest ‘Marvel Snap’ OTA Update Buff...
I don’t know about all of you, my fellow Marvel Snap (Free) players, but these days when I see a balance update I find myself clenching my… teeth and bracing for the impact to my decks. They’ve been pretty spicy of late, after all. How will the... | Read more »
‘Honkai Star Rail’ Version 2.4 “Finest D...
HoYoverse just announced the Honkai Star Rail (Free) version 2.4 “Finest Duel Under the Pristine Blue" update alongside a surprising collaboration. Honkai Star Rail 2.4 follows the 2.3 “Farewell, Penacony" update. Read about that here. | Read more »
‘Vampire Survivors+’ on Apple Arcade Wil...
Earlier this month, Apple revealed that poncle’s excellent Vampire Survivors+ () would be heading to Apple Arcade as a new App Store Great. I reached out to poncle to check in on the DLC for Vampire Survivors+ because only the first two DLCs were... | Read more »
Homerun Clash 2: Legends Derby opens for...
Since launching in 2018, Homerun Clash has performed admirably for HAEGIN, racking up 12 million players all eager to prove they could be the next baseball champions. Well, the title will soon be up for grabs again, as Homerun Clash 2: Legends... | Read more »
‘Neverness to Everness’ Is a Free To Pla...
Perfect World Games and Hotta Studio (Tower of Fantasy) announced a new free to play open world RPG in the form of Neverness to Everness a few days ago (via Gematsu). Neverness to Everness has an urban setting, and the two reveal trailers for it... | Read more »
Meditative Puzzler ‘Ouros’ Coming to iOS...
Ouros is a mediative puzzle game from developer Michael Kamm that launched on PC just a couple of months back, and today it has been revealed that the title is now heading to iOS and Android devices next month. Which is good news I say because this... | Read more »

Price Scanner via MacPrices.net

Amazon is still selling 16-inch MacBook Pros...
Prime Day in July is over, but Amazon is still selling 16-inch Apple MacBook Pros for $500-$600 off MSRP. Shipping is free. These are the lowest prices available this weekend for new 16″ Apple... Read more
Walmart continues to sell clearance 13-inch M...
Walmart continues to offer clearance, but new, Apple 13″ M1 MacBook Airs (8GB RAM, 256GB SSD) online for $699, $300 off original MSRP, in Space Gray, Silver, and Gold colors. These are new MacBooks... Read more
Apple is offering steep discounts, up to $600...
Apple has standard-configuration 16″ M3 Max MacBook Pros available, Certified Refurbished, starting at $2969 and ranging up to $600 off MSRP. Each model features a new outer case, shipping is free,... Read more
Save up to $480 with these 14-inch M3 Pro/M3...
Apple has 14″ M3 Pro and M3 Max MacBook Pros in stock today and available, Certified Refurbished, starting at $1699 and ranging up to $480 off MSRP. Each model features a new outer case, shipping is... Read more
Amazon has clearance 9th-generation WiFi iPad...
Amazon has Apple’s 9th generation 10.2″ WiFi iPads on sale for $80-$100 off MSRP, starting only $249. Their prices are the lowest available for new iPads anywhere: – 10″ 64GB WiFi iPad (Space Gray or... Read more
Apple is offering a $50 discount on 2nd-gener...
Apple has Certified Refurbished White and Midnight HomePods available for $249, Certified Refurbished. That’s $50 off MSRP and the lowest price currently available for a full-size Apple HomePod today... Read more
The latest MacBook Pro sale at Amazon: 16-inc...
Amazon is offering instant discounts on 16″ M3 Pro and 16″ M3 Max MacBook Pros ranging up to $400 off MSRP as part of their early July 4th sale. Shipping is free. These are the lowest prices... Read more
14-inch M3 Pro MacBook Pros with 36GB of RAM...
B&H Photo has 14″ M3 Pro MacBook Pros with 36GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 Pro MacBook Pro (... Read more
14-inch M3 MacBook Pros with 16GB of RAM on s...
B&H Photo has 14″ M3 MacBook Pros with 16GB of RAM and 512GB or 1TB SSDs in stock today and on sale for $150-$200 off Apple’s MSRP, each including free 1-2 day shipping: – 14″ M3 MacBook Pro (... Read more
Amazon is offering $170-$200 discounts on new...
Amazon is offering a $170-$200 discount on every configuration and color of Apple’s M3-powered 15″ MacBook Airs. Prices start at $1129 for models with 8GB of RAM and 256GB of storage: – 15″ M3... Read more

Jobs Board

*Apple* Systems Engineer - Chenega Corporati...
…LLC,** a **Chenega Professional Services** ' company, is looking for a ** Apple Systems Engineer** to support the Information Technology Operations and Maintenance Read more
Solutions Engineer - *Apple* - SHI (United...
**Job Summary** An Apple Solution Engineer's primary role is tosupport SHI customers in their efforts to select, deploy, and manage Apple operating systems and Read more
*Apple* / Mac Administrator - JAMF Pro - Ame...
Amentum is seeking an ** Apple / Mac Administrator - JAMF Pro** to provide support with the Apple Ecosystem to include hardware and software to join our team and Read more
Operations Associate - *Apple* Blossom Mall...
Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.