uchcode
11/1/2015 - 5:06 AM

DoShellScript.swift

/**
 Run executable.
 - parameter command: path to an executable file.
 - parameter withAdminPrivileges: execute with administrator privileges(sudo use case). defaut value is false.
 - returns: standard output in one string or nil when executable error.
 */
public func sh(command: String, withAdminPrivileges: Bool = false) -> String? {
    guard let res = NSBundle.mainBundle().resourcePath else {
        NSLog("Unexpected error while initializing resource path.")
        return nil
    }
    let cmd = command.stringByReplacingOccurrencesOfString("\\", withString:"\\\\")
    let adm = withAdminPrivileges ? " with administrator privileges" : ""
    let src = "do shell script \"cd \\\"\(res)\\\"; \(cmd)\"\(adm)"
    guard let script = NSAppleScript(source: src) else {
        NSLog("Unexpected error while initializing AppleScript: \(src)")
        return nil
    }
    var err : NSDictionary?
    let ret = script.executeAndReturnError(&err)
    if let e = err {
        NSLog("Unexpected error while executing AppleScript: \(e)")
        return nil
    }
    return ret.stringValue
}