mastige
mastige

Reputation: 21

How to escape single quote in appleScript/shell?

I have looked at this topic: single quote escaping in applescript/shell Although it was helpful, it does not quite solve my problem. This AppleScript snippet illustrates the problem:

set lastName to "O'Donnell"
set lastScript to "/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last '" & quoted form of (lastName & "'")
display dialog lastScript
do shell script lastScript

The property list file ".name.plist" in my home folder contains a key 'Last' to store the name 'O'Donnell'. The variable lastScript is passed as:

/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last ''O'\''Donnell'\'''

The script executes, but 'Last' is set to 'ODonnell' without the vital apostrophe. This is demonstrated by running this command in the shell:

/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Print Last'

PlistBuddy can be run in interactive mode:

/usr/libexec/PlistBuddy /Users/david/.name.plist

The command:

'Set Last O\'Donnell' 

successfully saves the name. What am I doing wrong?

Upvotes: 2

Views: 1032

Answers (1)

foo
foo

Reputation: 3259

Your escaping is messed up. Put the text value in double quotes to keep PlistBuddy happy, then single-quote the entire -c argument to keep bash happy:

to escapeDoubleQuotes(txt)
  set AppleScript's text item delimiters to "\\"
  set lst to txt's text items
  set AppleScript's text item delimiters to "\\\\"
  set txt to lst as text
  set AppleScript's text item delimiters to "\""
  set lst to txt's text items
  set AppleScript's text item delimiters to "\\\""
  return lst as text
end escapeDoubleQuotes

set lastName to "O'Donnell"

"/usr/libexec/PlistBuddy /Users/david/.name.plist -c " & quoted form of ("Set Last " & escapeDoubleQuotes(lastName))

--> "/usr/libexec/PlistBuddy /Users/david/.name.plist -c 'Set Last \"O'\\''Donnell\"'"

Upvotes: 1

Related Questions