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

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom 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.