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

Top Mobile Game Discounts
Every day, we pick out a curated list of the best mobile discounts on the App Store and post them here. This list won't be comprehensive, but it every game on it is recommended. Feel free to check out the coverage we did on them in the links... | Read more »
Price of Glory unleashes its 1.4 Alpha u...
As much as we all probably dislike Maths as a subject, we do have to hand it to geometry for giving us the good old Hexgrid, home of some of the best strategy games. One such example, Price of Glory, has dropped its 1.4 Alpha update, stocked full... | Read more »
The SLC 2025 kicks off this month to cro...
Ever since the Solo Leveling: Arise Championship 2025 was announced, I have been looking forward to it. The promotional clip they released a month or two back showed crowds going absolutely nuts for the previous competitions, so imagine the... | Read more »
Dive into some early Magicpunk fun as Cr...
Excellent news for fans of steampunk and magic; the Precursor Test for Magicpunk MMORPG Crystal of Atlan opens today. This rather fancy way of saying beta test will remain open until March 5th and is available for PC - boo - and Android devices -... | Read more »
Prepare to get your mind melted as Evang...
If you are a fan of sci-fi shooters and incredibly weird, mind-bending anime series, then you are in for a treat, as Goddess of Victory: Nikke is gearing up for its second collaboration with Evangelion. We were also treated to an upcoming... | Read more »
Square Enix gives with one hand and slap...
We have something of a mixed bag coming over from Square Enix HQ today. Two of their mobile games are revelling in life with new events keeping them alive, whilst another has been thrown onto the ever-growing discard pile Square is building. I... | Read more »
Let the world burn as you have some fest...
It is time to leave the world burning once again as you take a much-needed break from that whole “hero” lark and enjoy some celebrations in Genshin Impact. Version 5.4, Moonlight Amidst Dreams, will see you in Inazuma to attend the Mikawa Flower... | Read more »
Full Moon Over the Abyssal Sea lands on...
Aether Gazer has announced its latest major update, and it is one of the loveliest event names I have ever heard. Full Moon Over the Abyssal Sea is an amazing name, and it comes loaded with two side stories, a new S-grade Modifier, and some fancy... | Read more »
Open your own eatery for all the forest...
Very important question; when you read the title Zoo Restaurant, do you also immediately think of running a restaurant in which you cook Zoo animals as the course? I will just assume yes. Anyway, come June 23rd we will all be able to start up our... | Read more »
Crystal of Atlan opens registration for...
Nuverse was prominently featured in the last month for all the wrong reasons with the USA TikTok debacle, but now it is putting all that behind it and preparing for the Crystal of Atlan beta test. Taking place between February 18th and March 5th,... | Read more »

Price Scanner via MacPrices.net

AT&T is offering a 65% discount on the ne...
AT&T is offering the new iPhone 16e for up to 65% off their monthly finance fee with 36-months of service. No trade-in is required. Discount is applied via monthly bill credits over the 36 month... Read more
Use this code to get a free iPhone 13 at Visi...
For a limited time, use code SWEETDEAL to get a free 128GB iPhone 13 Visible, Verizon’s low-cost wireless cell service, Visible. Deal is valid when you purchase the Visible+ annual plan. Free... Read more
M4 Mac minis on sale for $50-$80 off MSRP at...
B&H Photo has M4 Mac minis in stock and on sale right now for $50 to $80 off Apple’s MSRP, each including free 1-2 day shipping to most US addresses: – M4 Mac mini (16GB/256GB): $549, $50 off... Read more
Buy an iPhone 16 at Boost Mobile and get one...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering one year of free Unlimited service with the purchase of any iPhone 16. Purchase the iPhone at standard MSRP, and then choose... Read more
Get an iPhone 15 for only $299 at Boost Mobil...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering the 128GB iPhone 15 for $299.99 including service with their Unlimited Premium plan (50GB of premium data, $60/month), or $20... Read more
Unreal Mobile is offering $100 off any new iP...
Unreal Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering a $100 discount on any new iPhone with service. This includes new iPhone 16 models as well as iPhone 15, 14, 13, and SE... Read more
Apple drops prices on clearance iPhone 14 mod...
With today’s introduction of the new iPhone 16e, Apple has discontinued the iPhone 14, 14 Pro, and SE. In response, Apple has dropped prices on unlocked, Certified Refurbished, iPhone 14 models to a... Read more
B&H has 16-inch M4 Max MacBook Pros on sa...
B&H Photo is offering a $360-$410 discount on new 16-inch MacBook Pros with M4 Max CPUs right now. B&H offers free 1-2 day shipping to most US addresses: – 16″ M4 Max MacBook Pro (36GB/1TB/... Read more
Amazon is offering a $100 discount on the M4...
Amazon has the M4 Pro Mac mini discounted $100 off MSRP right now. Shipping is free. Their price is the lowest currently available for this popular mini: – Mac mini M4 Pro (24GB/512GB): $1299, $100... Read more
B&H continues to offer $150-$220 discount...
B&H Photo has 14-inch M4 MacBook Pros on sale for $150-$220 off MSRP. B&H offers free 1-2 day shipping to most US addresses: – 14″ M4 MacBook Pro (16GB/512GB): $1449, $150 off MSRP – 14″ M4... Read more

Jobs Board

All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.