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

Go from lowly lizard to wicked Wyvern in...
Do you like questing, and do you like dragons? If not then boy is this not the announcement for you, as Loongcheer Game has unveiled Quest Dragon: Idle Mobile Game. Yes, it is amazing Square Enix hasn’t sued them for copyright infringement, but... | Read more »
Aether Gazer unveils Chapter 16 of its m...
After a bit of maintenance, Aether Gazer has released Chapter 16 of its main storyline, titled Night Parade of the Beasts. This big update brings a new character, a special outfit, some special limited-time events, and, of course, an engaging... | Read more »
Challenge those pesky wyverns to a dance...
After recently having you do battle against your foes by wildly flailing Hello Kitty and friends at them, GungHo Online has whipped out another surprising collaboration for Puzzle & Dragons. It is now time to beat your opponents by cha-cha... | Read more »
Pack a magnifying glass and practice you...
Somehow it has already been a year since Torchlight: Infinite launched, and XD Games is celebrating by blending in what sounds like a truly fantastic new update. Fans of Cthulhu rejoice, as Whispering Mist brings some horror elements, and tests... | Read more »
Summon your guild and prepare for war in...
Netmarble is making some pretty big moves with their latest update for Seven Knights Idle Adventure, with a bunch of interesting additions. Two new heroes enter the battle, there are events and bosses abound, and perhaps most interesting, a huge... | Read more »
Make the passage of time your plaything...
While some of us are still waiting for a chance to get our hands on Ash Prime - yes, don’t remind me I could currently buy him this month I’m barely hanging on - Digital Extremes has announced its next anticipated Prime Form for Warframe. Starting... | Read more »
If you can find it and fit through the d...
The holy trinity of amazing company names have come together, to release their equally amazing and adorable mobile game, Hamster Inn. Published by HyperBeard Games, and co-developed by Mum Not Proud and Little Sasquatch Studios, it's time to... | Read more »
Amikin Survival opens for pre-orders on...
Join me on the wonderful trip down the inspiration rabbit hole; much as Palworld seemingly “borrowed” many aspects from the hit Pokemon franchise, it is time for the heavily armed animal survival to also spawn some illegitimate children as Helio... | Read more »
PUBG Mobile teams up with global phenome...
Since launching in 2019, SpyxFamily has exploded to damn near catastrophic popularity, so it was only a matter of time before a mobile game snapped up a collaboration. Enter PUBG Mobile. Until May 12th, players will be able to collect a host of... | Read more »
Embark into the frozen tundra of certain...
Chucklefish, developers of hit action-adventure sandbox game Starbound and owner of one of the cutest logos in gaming, has released their roguelike deck-builder Wildfrost. Created alongside developers Gaziter and Deadpan Games, Wildfrost will... | Read more »

Price Scanner via MacPrices.net

Limited-time sale: 13-inch M3 MacBook Airs fo...
Amazon has the base 13″ M3 MacBook Air (8GB/256GB) in stock and on sale for a limited time for $989 shipped. That’s $110 off MSRP, and it’s the lowest price we’ve seen so far for an M3-powered... Read more
13-inch M2 MacBook Airs in stock today at App...
Apple has 13″ M2 MacBook Airs available for only $849 today in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty is included,... Read more
New today at Apple: Series 9 Watches availabl...
Apple is now offering Certified Refurbished Apple Watch Series 9 models on their online store for up to $80 off MSRP, starting at $339. Each Watch includes Apple’s standard one-year warranty, a new... Read more
The latest Apple iPhone deals from wireless c...
We’ve updated our iPhone Price Tracker with the latest carrier deals on Apple’s iPhone 15 family of smartphones as well as previous models including the iPhone 14, 13, 12, 11, and SE. Use our price... Read more
Boost Mobile will sell you an iPhone 11 for $...
Boost Mobile, an MVNO using AT&T and T-Mobile’s networks, is offering an iPhone 11 for $149.99 when purchased with their $40 Unlimited service plan (12GB of premium data). No trade-in is required... Read more
Free iPhone 15 plus Unlimited service for $60...
Boost Infinite, part of MVNO Boost Mobile using AT&T and T-Mobile’s networks, is offering a free 128GB iPhone 15 for $60 per month including their Unlimited service plan (30GB of premium data).... Read more
$300 off any new iPhone with service at Red P...
Red Pocket Mobile has new Apple iPhones on sale for $300 off MSRP when you switch and open up a new line of service. Red Pocket Mobile is a nationwide MVNO using all the major wireless carrier... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, available for $759 for 8-Core CPU/7-Core GPU/256GB models and $929 for 8-Core CPU/8-Core GPU/512GB models. Apple’s one-year warranty is... Read more
Updated Apple MacBook Price Trackers
Our Apple award-winning MacBook Price Trackers are continually updated with the latest information on prices, bundles, and availability for 16″ and 14″ MacBook Pros along with 13″ and 15″ MacBook... Read more
Every model of Apple’s 13-inch M3 MacBook Air...
Best Buy has Apple 13″ MacBook Airs with M3 CPUs in stock and on sale today for $100 off MSRP. Prices start at $999. Their prices are the lowest currently available for new 13″ M3 MacBook Airs among... Read more

Jobs Board

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
DMR Technician - *Apple* /iOS Systems - Haml...
…relevant point-of-need technology self-help aids are available as appropriate. ** Apple Systems Administration** **:** Develops solutions for supporting, deploying, Read more
Omnichannel Associate - *Apple* Blossom Mal...
Omnichannel Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple 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.