How to run shell commands from a Mac / MacRuby app?

I am trying to write a small MacRuby status bar application that launches a command from the command line and displays the result. I do not know how to do that. How can I do this from my Mac application?

Update: Another that may be required is to ask for an administrator password. Sometimes, when I run this script from the command line, it asks for my password. I do not know how I will offer the user a password (or embed a shell so that they can type it directly).

+5
source share
2 answers

Using Cocoa and MacRuby, use NSTask. An example that produces the output of ls -la and prints:

framework 'Cocoa'

task = NSTask.alloc.init
task.setLaunchPath("/bin/ls")

arguments = NSArray.arrayWithObjects("-l", "-a", nil)
task.setArguments(arguments)

pipe = NSPipe.pipe
task.setStandardOutput(pipe)

file = pipe.fileHandleForReading

task.launch

data = file.readDataToEndOfFile

string = NSString.alloc.initWithData(data, encoding: NSUTF8StringEncoding)
puts "Command returned: "
puts string

Unfortunately, including administrator privileges there is no trivial task, especially using MacRuby. Take a look at the SecurityFoundation infrastructure and link. Essentially you need to call

AuthorizationExecuteWithPrivileges(...)

with the configured AuthorizationRef parameter, the way the tool is executed, flags, arguments. Here's a useful example here (in ObjC) showing how this works.

+6
source

You can simply use backlinks:

output = `cd ~ && ls`
puts output # or assign to a label, textbox etc.

If your team needs administrator privileges to run, it will not run the command at all and will not return a response.

+1
source

All Articles