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

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 »
MoreFun Studios has announced Season 4,...
Tension has escalated in the ever-volatile world of Arena Breakout, as your old pal Randall Fisher and bosses Fred and Perrero continue to lob insults and explosives at each other, bringing us to a new phase of warfare. Season 4, Into The Fog of... | Read more »
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 below... | Read more »
Marvel Future Fight celebrates nine year...
Announced alongside an advertising image I can only assume was aimed squarely at myself with the prominent Deadpool and Odin featured on it, Netmarble has revealed their celebrations for the 9th anniversary of Marvel Future Fight. The Countdown... | Read more »
HoYoFair 2024 prepares to showcase over...
To say Genshin Impact took the world by storm when it was released would be an understatement. However, I think the most surprising part of the launch was just how much further it went than gaming. There have been concerts, art shows, massive... | Read more »

Price Scanner via MacPrices.net

Apple Watch Ultra 2 now available at Apple fo...
Apple has, for the first time, begun offering Certified Refurbished Apple Watch Ultra 2 models in their online store for $679, or $120 off MSRP. Each Watch includes Apple’s standard one-year warranty... Read more
AT&T has the iPhone 14 on sale for only $...
AT&T has the 128GB Apple iPhone 14 available for only $5.99 per month for new and existing customers when you activate unlimited service and use AT&T’s 36 month installment plan. The fine... Read more
Amazon is offering a $100 discount on every M...
Amazon is offering a $100 instant discount on each configuration of Apple’s new 13″ M3 MacBook Air, in Midnight, this weekend. These are the lowest prices currently available for new 13″ M3 MacBook... Read more
You can save $300-$480 on a 14-inch M3 Pro/Ma...
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
24-inch M1 iMacs available at Apple starting...
Apple has clearance M1 iMacs available in their Certified Refurbished store starting at $1049 and ranging up to $300 off original MSRP. Each iMac is in like-new condition and comes with Apple’s... Read more
Walmart continues to offer $699 13-inch M1 Ma...
Walmart continues to offer 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 MacBook for sale by... Read more
B&H has 13-inch M2 MacBook Airs with 16GB...
B&H Photo has 13″ MacBook Airs with M2 CPUs, 16GB of memory, and 256GB of storage in stock and on sale for $1099, $100 off Apple’s MSRP for this configuration. Free 1-2 day delivery is available... Read more
14-inch M3 MacBook Pro with 16GB of RAM avail...
Apple has the 14″ M3 MacBook Pro with 16GB of RAM and 1TB of storage, Certified Refurbished, available for $300 off MSRP. Each MacBook Pro features a new outer case, shipping is free, and an Apple 1-... Read more
Apple M2 Mac minis on sale for up to $150 off...
Amazon has Apple’s M2-powered Mac minis in stock and on sale for $100-$150 off MSRP, each including free delivery: – Mac mini M2/256GB SSD: $499, save $100 – Mac mini M2/512GB SSD: $699, save $100 –... Read more
Amazon is offering a $200 discount on 14-inch...
Amazon has 14-inch M3 MacBook Pros in stock and on sale for $200 off MSRP. Shipping is free. Note that Amazon’s stock tends to come and go: – 14″ M3 MacBook Pro (8GB RAM/512GB SSD): $1399.99, $200... Read more

Jobs Board

Housekeeper, *Apple* Valley Village - Cassi...
Apple Valley Village Health Care Center, a senior care campus, is hiring a Part-Time Housekeeper to join our team! We will train you for this position! In this role, Read more
Sublease Associate Optometrist- *Apple* Val...
Sublease Associate Optometrist- Apple Valley, CA- Target Optical Date: Apr 20, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92307 **Requisition Read more
*Apple* Systems Administrator - JAMF - Syste...
Title: Apple Systems Administrator - JAMF ALTA is supporting a direct hire opportunity. This position is 100% Onsite for initial 3-6 months and then remote 1-2 Read more
Relationship Banker - *Apple* Valley Financ...
Relationship Banker - Apple Valley Financial Center APPLE VALLEY, Minnesota **Job Description:** At Bank of America, we are guided by a common purpose to help Read more
IN6728 Optometrist- *Apple* Valley, CA- Tar...
Date: Apr 9, 2024 Brand: Target Optical Location: Apple Valley, CA, US, 92308 **Requisition ID:** 824398 At Target Optical, we help people see and look great - and Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.