0

I have the following function:

func executeCommandAsAdminWithAppleScript(command: String, inout output: String?, inout errorDesc: String?) -> Bool {
    var errorInfo: NSDictionary?
    let source = "do shell script \"\(command)\" with administrator privileges"
    let script = NSAppleScript(source: source)
    let eventResult = script?.executeAndReturnError(&errorInfo)

    if eventResult == nil {
        errorDesc = nil
        if let code = errorInfo?.valueForKey(NSAppleScriptErrorNumber) as? NSNumber {
            if code.intValue == -128 {
                errorDesc = "The administrator password is required to do this.";
            }

            if errorDesc == nil {
                if let message = errorInfo?.valueForKey(NSAppleScriptErrorMessage) as? NSString {
                    errorDesc = String(message)
                }
            }
        }
        return false
    } else {
        output = (eventResult?.stringValue)!
        return true
    }
}

This function basically runs a command with admin privileges. Now I try to execute commands like echo Hello World, the output parameter does have a string that looks like Hello World, which is outputted into stdout. But when I tried to execute commands that output data into stderr, the output cannot retrieve the data. So is there a way to retrieve data in stderr without using NSTask? Thanks.

3
  • Maybe set command to command 2>&1 so it returns both stdout and stderr. Commented Apr 25, 2016 at 11:05
  • @MarkSetchell thanks, you can post this as an answer now Commented Apr 25, 2016 at 13:20
  • Sure, I have done - glad it worked out for you. Commented Apr 25, 2016 at 13:22

1 Answer 1

2

Where you use command in your script, try replacing it with

command 2>&1

as that will combine the standard error stream (2) with the standard out stream (1) and then you will get them both returned to you.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.