Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I escape shell arguments in AppleScript?

Applescript does not seem to properly escape strings. What am I doing wrong?

Example:

set abc to "funky-!@#'#\"chars"
display dialog abc
display dialog quoted form of abc

Expected / Desired Output:

funky-!@#'#"chars
'funky-!@#\'#"chars'

Actual Output:

funky-!@#'#"chars
'funky-!@#'\''#"chars'

As you can see, it appears that in the actual output Applescript is adding and escaping an extra '

I would be OK with the end characters being either ' or " and I would also be fine with both the single and double quotes being escaped - but it appears that only the single quotes are actually escaped.

like image 961
cwd Avatar asked Nov 15 '11 14:11

cwd


People also ask

Does AppleScript have script commands?

In AppleScript, the do shell script command is used to execute command-line tools. This command is implemented by the Standard Additions scripting addition included with OS X. The Terminal app in /Applications/Utilities/ is scriptable and provides another way to execute command-line tools from scripts.

Do shell scripts command?

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).


1 Answers

Backslashes aren't usually interpreted inside single quotes in shells.

Enclosing characters in single quotation marks preserves the literal value of each character within the single quotation marks. A single quotation mark cannot occur within single quotation marks.

A backslash cannot be used to escape a single quotation mark in a string that is set in single quotation marks. An embedded quotation mark can be created by writing, for example: 'a'\''b', which yields a'b.

However they are interpreted by echo in sh, which is the shell used by do shell script:

do shell script "echo " & quoted form of "\\t" --> "\t"

Unsetting xpg_echo makes it behave like the echo in bash:

do shell script "shopt -u xpg_echo; echo " & quoted form of "\\t" --> "\\t"

Often it's simpler to use HEREDOC redirection instead:

do shell script "rev <<< " & quoted form of "a\\tb" --> "b\\ta"
like image 159
Lri Avatar answered Sep 21 '22 18:09

Lri