2

Newbee question -

Now that OSX/Script Editor.app can do javascript, how do I change my applescript set a to (do shell script "ls") to the javascript syntax?

From what I'm reading in the StandardAdditions.sdef, "doShellScript method : Execute a shell script using the ‘sh’ shell" is the command, so I tried, doShellScript "ls" , and the Script Editor (with the Script Language is set to JavaScript) returns,

"Error -2700: Script error."

1 Answer 1

4

You have to tell your JXA script to use the Standard Additions.

app = Application.currentApplication()
app.includeStandardAdditions = true

sourcePath = "/Applications"

// Do not use! Unsafe path-quoting can lead to injection and unwanted behavior! See the update below for the safe version!
app.doShellScript("ls '" + sourcePath + "'").split("\r")

UPDATE: EDIT After being slapped on the hand by @foo for using a fairly unsafe path-quoting method, the new answer is this:

app = Application.currentApplication()
app.includeStandardAdditions = true

sourcePath = "/Applications"

// Safe version!
app.doShellScript("ls '" + sourcePath.replace("'", "'\\''") + "'")

Enjoy, Michael / Hamburg

Sign up to request clarification or add additional context in comments.

4 Comments

That did it. Thank you.
@Shoo: Your example is dangerously unsafe! What happens if sourcePath contains a single quote mark, e.g. "/Users/jsmith/Bob's stuff"? You must sanitize your inputs when munging them into a new shell script, e.g. doShellScript("ls '" + sourcePath.replace("'", "'\\''") + "'"). If you don't, at best your shell script will fail to run; at worst it will do totally the wrong thing. For example, what if you'd been using rm -rf instead? Gods help you if you had another folder named "Bob" on there full of important files, 'cos—Surprise!—now you don't. Always sanitize, sanitize, sanitize!
@foo: Yes, of course you are right, thank you! My fast written solution just scoped the doShellScript, but we as community should take care when answering, especially for Newbies or even for Newbies that will read the answer later! I'll update my answer.
@CRGreen I quoted you. Your answer being slapped on the hand just hit the point :-D

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.