简体   繁体   English

Applescript不执行Shell命令

[英]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"! 但是file.txt不包含“ aaa”!

It contains "-n -e aaa\\n" instead. 它改为包含“ -n -e aaa \\ n”。

Can someone help me with that problem? 有人可以帮我解决这个问题吗?

Different versions of echo are hopelessly inconsistent in how they interpret command options (like -n and -e ) and/or escape sequences in the string. echo不同版本在解释字符串中的命令选项(如-n-e )和/或转义序列的方式上毫无希望地不一致。 It's not just bash vs. sh as cdarke said; 正如cdarke所说的,不仅仅是bashvs.sh。 it's much messier than that. 比这更混乱。 The best thing to do is just avoid either one by using printf instead. 最好的办法是通过使用printf来避免任何一个。 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(!). 使用它比echo要复杂一些,但是完全值得,因为您的脚本不会因为仅使用不同的options(!)编译最新版的Shell而中断。

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). 在这种情况下,使用printf实际上比使用echo还要简单,因为它总是解释转义序列(在第一个参数中,是“格式字符串”,其余部分是不同的),并且不会在末尾打印换行符(除非您在格式字符串的末尾用\\n明确告诉它)。 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 : ...尽管您可以通过使用单引号进一步简化它,以防止外壳程序在转义到达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.) (转义符仍然加倍,因为它们已被AppleScript解释。但是至少它们不再需要四倍了。)

(ps relevant xkcd ) (ps 相关的xkcd

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM