single quote escaping in applescript/shell - shell

I'm trying to process this shell script in applescript, but it keeps saying error EOF, because of the single quote in the folder name.
do shell script "cp -R " & a & " " & "'" & d & "/My 'Folder/java/" & "'"
The folder /My 'Folder/ is a legitimate directory.
The variable a = '/Applications/MyProgram/' (and includes the single quotes)
The variable d = /Folders (with no single quotes)
However, shell is getting stuck processing it, im guessing because the folder is enclosed in quotes.
Is there any way to escape this single quote, so it works in applescript using shell? Ive tried multiple backslashes but its not working.
Cheers
N

Always use quoted form of when using arbitrary data as an argument to an command. This will always quote the value even if it doesn't need to be quoted but it's better safe than sorry. When you have a string single quoted, you can only unquote (turn substitution mode back on) with another quote. Unlike AppleScript strings, you can't escape characters inside single quoted strings. So you need to turn substitution mode on, escape a quote and then turn substitution mode back one. For instance "Joe's car" should be quoted as "'Joe'\\''s car'". It's a quoted string "Joe" + escaped quote character + quoted string "s car". But like I started you should use quoted form of, quoted form of "Joe's car" will return "'Joe'\\''s car'"
Your command using quoted form will look like:
do shell script "cp -R " & quoted form of a & space & quoted form of (d & "/My 'Folder/java/")

The problem arises because you have that tick in the filename of course, on the terminal commandline you would use a tick - double-tick tick - double-tick tick sequence to present it.
(From the terminal below)
729$ echo 'My '"'"'Java Folder'
My 'Java Folder
In Applescript, and your command line, it becomes even more complicated, I recommend you echo your commandline, until you get back what you expect.
set res to (do shell script "echo 'My '\"'\"'Java Folder'")
log res
--> (*My 'Java Folder*)
I think you'll have to start out with that, and reconstruct how you escape the rest of the commandline around it, if it can't be just plugged in as it is.
You should also remove single quotes for entities, that doesn't need them, (no spaces). That way your commandline will become easier to both edit and read.

Adding an answer for JavaScript for AppleScript (JAX) users based on answer from McUsr:
debugger
var app = Application.currentApplication();
app.includeStandardAdditions = true;
var source = "/documents/John's Spreadsheet.xls";
var target = "/documents/John's Spreadsheet.csv";
source = source.replace("'", "'\"'\"'", "g");
target = target.replace("'", "'\"'\"'", "g");
var exportScript = "/excel -i";
exportScript += " '" + source + "'";
exportScript += " '" + target + "'";
exportScript += ";true";
try {
app.doShellScript(exportScript);
}
catch (error) {
console.log(error.message);
}
If you don't know what JAX is it's AppleScript but using JavaScript. Open Script Editor and select JavaScript from the dropdown beneath the record button.

Related

The system cannot find the file if its path/name contains a space

Path = split(wscript.scriptFullName, wscript.scriptname)(0)
CreateObject("wscript.shell").run(Path & "Name.txt")
The above script works fine if both the file path and file name contain no spaces.
If either contains a space, the result will be;
Error: The system cannot find the file specified.
How can I fix the error?
The rules are fairly simple:
All strings have to start and end with double quotes to be a valid string.
Dim a
a = "Hello World" 'Valid string.
a = "Hello World 'Not valid and will produce an error.
Any use of variables must use the String Concatenation character & to combine them with strings.
Dim a: a = "Hello"
Dim b
b = a & " World" 'Valid concatenated string.
b = a " World" 'Not valid and will produce an error.
As double quotes are used to define a string, all instances of double quotes inside a string must be escaped by doubling the quotes "" but Rule 1. still applies.
Dim a: a = "Hello"
Dim b
b = """" & a & " World""" 'Valid escaped string.
b = """ & a & " World""" 'Not valid, start of string is not complete
'after escaping the double quote
'producing an error.
Follow these three rules and you won't go far wrong.
With those in mind the above line would need to be;
CreateObject("wscript.shell").run("""" & Path & "Name.txt""")
to generate a string surrounded by literal double quotes.
Useful Links
VBS with Space in File Path
Adding quotes to a string in VBScript
Breaking a String Across Multiple Lines (More on string concatenation).
CreateObject("wscript.shell").run(""""Path & "Name.txt""")
is how.

Opening chrome browser with disabled websecurity [duplicate]

I want to insert an if statement in a cell through vba which includes double quotes.
Here is my code:
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)"
Due to double quotes I am having issues with inserting the string. How do I handle double quotes?
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard",
In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.
In case the comment by gicalle ever dies:
I prefer creating a global variable:
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')
and using it like so:
Shell "explorer.exe " & vbDoubleQuote & sPath & vbDoubleQuote, vbNormalFocus

How to encapsulate a very long string in quotation marks?

I want to print a long VBScript program into a file as one string.
program_str = " long 200 line program"
However, placing quotation marks around so long a string does not work, as it stops recognizing the program as a string as soon as it hits another set of quotation marks. Short of separating each line of the program, and concatenating it, how could I take this long program as a string and paste it into a file?
Two options:
Double any quotes in your string literal:
program_str = "This program has a quote like this "" in it."
Use Chr(34) to specify a quote in your string literal (requires concatenating):
program_str = "This program has a quote like this " & Chr(34) & " in it."
If you want to include speech marks in a string, you must precede each of them with another quotation mark "
e.g.
program_str = "He said ""Hello"""

Can a variable act as a space in VBS?

I'm teaching myself VBS and I decided to write a message encryption program. It uses the left and right functions in a loop to read every individual character.
DO
wscript.sleep 100
if Az=0 then
EXIT DO
end if
CR=right(message,aZ)
DEL=left(CR,1)
aZ=aZ-1
zZ=zZ+1
supra=""
supra="supra"
CALL KEYCOUNT
CD=left(keyword,zZ)
TAC=right(CD,1)
....
From there, it sets every character equal to a different letter based on an encryption keyword and moves onto the next character. My problem is I don't know how to deal with spaces in the message. Is there a way to make a variable have the value of a space? I've tried:
set var=space(1)
set var="&"" ""&"
set var=""
set var=" "
set var=""" """
I'm certain there are things I'm not thinking of
Thanks
Joseph
set statement assigns an object reference to a variable or property, or associates a procedure reference with an event. That isn't our case.
var=space(1) ' var contains one space character
var="&"" ""&" ' var contains &" "&
var="" ' var contains a string of zero length
var=" " ' var contains one space character
var=""" """ ' var contains " "
Or, if you would like, declare a constant for use in place of literal value of space (anywhere in your script) as follows:
Const vbSp=" "
Constants are public by default. Within procedures, constants are always private; their visibility can't be changed. Within a script, the default visibility of a script-level constant can be changed using the Private keyword. There are variations:
Private Const vbSp=" "
Public Const vbSp=" "
The problem is that you use Set (cf. here) when assigning a simple/non-object value to a variable. If you loose it, your experimental statements will 'work' (compile & run without error). Look at the output and you'll see that
var = " "
is the correct and most efficient way to assign a (string containing one) space to a variable.

Pipe to subprocess stdin for JXA

I would like to start a subprocess in JavaScript for Automation (JXA) and send a string to that subprocess's stdin which might include newlines, shell metas, etc. Previous AppleScript approaches for this used bash's <<< operator, string concatenation, and quoted form of the string. If there was a JavaScript equivalent of quoted form of that I could trust to get all of the edge cases, I could use the same approach; I'm investigating regex methods toward that end.
However, I thought since we have access to unistd.h from JXA, why not try to just call $.pipe, $.fork, and $.execlp directly? $.pipe looks like it should take an array of 2 integers as its parameter, but none of the things that I have tried worked:
ObjC.import('unistd')
$.pipe() // Error: incorrect number of arguments
$.pipe([]) // segfault
$.pipe([3,4]) // segfault
$.pipe([$(), $()]) // segfault
var a = $(), b=$()
$.pipe([a,b]) // segfault
$.pipe($([a,b])) // NSException without a terribly helpful backtrace
$.pipe($([$(3), $(4)])) // segfault
var ref = Ref('int[2]')
$.pipe(ref)
ref[0] // 4, which is close!
Any suggestions?
I found an approach that works, using Cocoa instead of stdio:
ObjC.import('Cocoa')
var stdin = $.NSPipe.pipe
var stdout = $.NSPipe.pipe
var task = $.NSTask.alloc.init
task.launchPath = "/bin/cat"
task.standardInput = stdin
task.standardOutput = stdout
task.launch
var dataIn = $("foo$HOME'|\"").dataUsingEncoding($.NSUTF8StringEncoding)
stdin.fileHandleForWriting.writeData(dataIn)
stdin.fileHandleForWriting.closeFile
var dataOut = stdout.fileHandleForReading.readDataToEndOfFile
var stringOut = $.NSString.alloc.initWithDataEncoding(dataOut, $.NSUTF8StringEncoding).js
console.log(stringOut)
It is indeed curious that there appears to be no JXA equivalent of AppleScript's quoted form of for safely passing script literals to shell commands.
However, it is fairly easy to implement:
// JXA implementation of AppleScript's `quoted form of`
function quotedForm(s) { return "'" + s.replace(/'/g, "'\\''") + "'" }
// Example
app = Application.currentApplication();
app.includeStandardAdditions = true;
console.log(app.doShellScript('cat <<<' + quotedForm("foo$HOME'|\"")))
Credit for quotedForm() goes to this comment.
As far as I can tell, this implementation does the same as quoted form of does:
In the simplest form, if the string contains no embedded single-quotes, it single-quotes the entire string; since POSIX-like shells perform no interpolation whatsoever on a single-quoted string, it is preserved as-is.
If the string does contain embedded single-quotes, it is effectively broken into multiple single-quoted strings, with each embedded single-quote spliced in as \' (backslash-escaped) - this is necessary, because it is not possible to embed single-quotes in single-quoted literal in POSIX-compatible shells.
In a POSIX-compatible shell, this should work for all strings.
The quotedForm function above (below?) is lacking one very important feature, it only quotes/escapes the first in-line apostrophe whereas it needs to deal with however many exist in the string.
I changed it to this which seems to work:-
// JXA implementation of AppleScript's `quoted form of`
function quotedFormOf(s) { return "'" + s.replace(/'/g, "'\\''") + "'" }

Resources