Jan Jan - 1 year ago 128
AppleScript Question

Applescript does not execute shell command

I have an applescript

do shell script "echo -n -e \\\\x61\\\\x61\\\\x61 > /tmp/file.txt"

But the file.txt does not contain "aaa"!

It contains "-n -e aaa\n" instead.

Can someone help me with that problem?

Answer Source

Different versions of echo are hopelessly inconsistent in how they interpret command options (like -n and -e) and/or escape sequences in the string. It's not just bash vs. sh as cdarke said; it's much messier than that. The best thing to do is just avoid either one by using printf instead. It's a bit more complicated to use than echo, but completely worth it because your scripts won't break just because the latest version of the shell was compiled with different options(!).

In this case, using printf is actually even simpler than using echo, because it always interprets escape sequences (in its first argument, the "format string" -- the rest are different), and doesn't print a newline at the end (unless you explicitly tell it to with \n at the end of the format string). So your script becomes:

do shell script "printf \\\\x61\\\\x61\\\\x61 > /tmp/file.txt"

...although you can simplify it further by using single-quotes to keep the shell from interpreting escapes before they get to printf:

do shell script "printf '\\x61\\x61\\x61' > /tmp/file.txt"

(The escapes are still doubled, because they're being interpreted by AppleScript. But at least they don't need to be quadrupled anymore.)

(p.s. relevant xkcd)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download