13.15. The do shell script Command

Sometimes you just can't do everything you need to do in AppleScript. The do shell script command lets you execute any other command on the system and capture its output. If you're an experienced UNIX user, you understand that this command passes a command line to the UNIX shell for execution and captures its output (written to standard output).

The ls command without any additional arguments lists the files in your current directory. Here's how to execute the command from AppleScript and capture its output in your program:

set files to do shell script "ls"

This is a less efficient approach than using AppleScript's list files command, which is handled directly by AppleScript. The do shell script command must start up another process (the shell) and ask it to execute the specified command line.

To get a list of the files in your Documents folder, you could give ls the name of the folder to list as an argument:

do shell script "ls " & POSIX path of (path to documents folder as string)

All UNIX commands use POSIX paths, so you convert any Mac-style paths as necessary. In the next example, the shell's printf command is used to format the value of pi to two decimal places:

set x to pi
set cmdLine to "printf " & "%.2f" & " " & pi
do shell script cmdLine

Here's the result that is returned from the do shell script command:

"3.14"

This is useful for formatting numbers, which is not easy to do in AppleScript (you can write a special handler ...

Get Beginning AppleScript® now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.