Skip to content

Instantly share code, notes, and snippets.

@uchcode
Created November 1, 2015 05:06
Show Gist options
  • Save uchcode/5a331d5dbb328c172119 to your computer and use it in GitHub Desktop.
Save uchcode/5a331d5dbb328c172119 to your computer and use it in GitHub Desktop.
/**
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
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment