2

After repeated searching I have not found an elegant solution to this issue: how to run a shell command in obj-c and get it's output. I have read many questions regarding this, but they all fail to answer my question.

Some get the exit value ( Get result from shell script objective-c ) others only run the command ( Cocoa/ Objective-C Shell Command Line Execution ), and finally others have me write the output to a file ( Execute a terminal command from a Cocoa app ).

I really would like to avoid writing/reading a file as it not a very clean solution.

Is there no way to read the output directly in obj-c? If so how?

Community
  • 1
  • 1
Trcx
  • 4,164
  • 6
  • 30
  • 30
  • Please reformat your question for better readability. – tobiasbayer Dec 28 '11 at 22:50
  • Sorry, I made the assumption that the backend would automatically parse the urls. – Trcx Dec 28 '11 at 22:51
  • Some paragraphs would also be a great improvement. – tobiasbayer Dec 28 '11 at 22:56
  • this is confusing. Are you running the shell command in cocoa? (in app?) or in the terminal? – Neilvert Noval Dec 29 '11 at 02:16
  • In my intended application I would be running the command on a jail broken iOS device and then working with the output to create a nice table. I want the user to be able to pass custom arguments to the command, otherwise I would just integrate the C code directly. – Trcx Dec 29 '11 at 18:13

3 Answers3

2

The code from "doshellscript" from the first link (Get result from shell script objective-c) actually does return an NSString with the output of the command. If it's not working for you, maybe the command is outputting over stderr rather than stdin? Have you tried this yet? The standard mechanism for running commands in Cocoa is NSTask, so definitely at least start there.

Community
  • 1
  • 1
Jared Pochtar
  • 4,925
  • 2
  • 29
  • 39
  • Thank you for pointing this out, Originally I miss read this as reading from a temporary file and getting the exit code of the script, blame it my reading it at 2:30 am. With a clear(er) head this morning I was able to take apart the function and get it to work. – Trcx Dec 29 '11 at 18:11
2

Look at the class PRHTask. It is a replacement of NSTask, with completion blocks. https://bitbucket.org/boredzo/prhtask

Extract from the header:

  • First, rather than having to set your own pipe for standard output and error, you can tell the task to accumulate the output for you, and retrieve it when the task completes.
  • Second, when the process exits, rather than posting an NSNotification, a PRHTask will call either of two blocks that you provide. You can set them both to the same block if you want.
Guillaume
  • 21,685
  • 6
  • 63
  • 95
0

If your task needs admin privileges, you might want to look at STPrivilegedTask.

svth
  • 1,303
  • 1
  • 14
  • 23