Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

xcode 6 swift system() command

Tags:

macos

swift

Is there a good description of swift system command? For example, this code

    let x = system("ls -l `which which`")
    println(x)

produces -rwxr-xr-x 1 root wheel 14496 Aug 30 04:29 /usr/bin/which

0

I would like to separate the output from the return code

like image 621
Lanny Rosicky Avatar asked Oct 16 '14 08:10

Lanny Rosicky


1 Answers

system() is not a Swift command but a BSD library function. You get the documentation with "man system" in a Terminal Window:

The system() function hands the argument command to the command interpreter sh(1). The calling process waits for the shell to finish executing the command, ignoring SIGINT and SIGQUIT, and blocking SIGCHLD.

The output of the "ls" command is just written to the standard output and not to any Swift variable.

If you need more control then you have to use NSTask from the Foundation framework. Here is a simple example:

let task = NSTask()
task.launchPath = "/bin/sh"
task.arguments = ["-c", "ls -l `which which`"]

let pipe = NSPipe()
task.standardOutput = pipe
task.launch()

let data = pipe.fileHandleForReading.readDataToEndOfFile()
if let output = NSString(data: data, encoding: NSUTF8StringEncoding) {
    println(output)
}

task.waitUntilExit()
let status = task.terminationStatus
println(status)

Executing the command via the shell "/bin/sh -c command ..." is necessary here because of the "back tick" argument. Generally, it is better to invoke the commands directly, for example:

task.launchPath = "/bin/ls"
task.arguments = ["-l", "/tmp"]
like image 147
Martin R Avatar answered Nov 27 '22 11:11

Martin R