alexsius
alexsius

Reputation: 43

Swift invalid escape sequence in literal

If I try to compile I receive "invalid escape sequence in literal" error because of "\;" but if I try to use "\\;" or "\u{005C};" I receive error find: -exec: no terminating ";" or "+" like I am not passing the backslash character

@IBAction func button1(_ sender: NSButton) {

    let path = "/usr/bin/find"
    let arguments = ["folder_path","-name","'*.docx'","-print","-exec","zip","'{}'.zip","'{}'","\;"]

    sender.isEnabled = false

    let task = Process.launchedProcess(launchPath :path, arguments: arguments)

    task.waitUntilExit()

    sender.isEnabled = true
}

Upvotes: 0

Views: 4378

Answers (2)

matt
matt

Reputation: 535306

As Rob says (and as I had gently suggested in my comments), you are not in a shell, so you do not need any special quoting or backslashing.

There's no way I am going to execute a zip command on my machine, so I tested like this:

let task = Process()
task.launchPath = "/usr/bin/find"
task.arguments = 
    ["/Users/matt/Desktop", "-name", "*.mp3", "-exec", "echo", "{}", ";"]

With appropriate pipe configured, I ran the task and read from the pipe and sure enough, we found the one mp3 file on my Desktop. Notice that no arguments are single-quoted or backslashed.

Upvotes: 2

Rob Napier
Rob Napier

Reputation: 299355

You've added a bunch of shell-escapes when you're not passing this to a shell. For example:

"'*.docx'"

In this context, this literally mean '*.docx', with the extra '. Those are included when you call the shell because otherwise the shell would expand the *. But again, no shell. So nothing is removing them for you. Same issue for the ;. You just want a ;, which is required by -exec. But there's no shell in the way, so you don't need a backslash because nothing would eat the ;.

You mean:

let arguments = ["folder_path","-name","*.docx","-print","-exec","zip","{}.zip","{}",";"]

Upvotes: 1

Related Questions