0

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?

2
  • 1
    sh echo does not support -n or -e options, they are a bash extension. Try prefixing the command with bash -c Commented Aug 25, 2016 at 14:36
  • Or see if your system supports printf . Good luck. Commented Aug 25, 2016 at 14:46

1 Answer 1

2

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)

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

1 Comment

Plus one for "relevant xkcd". Link still good four years later.

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.