How can I execute a terminal command (like grep) from my Objective-C Cocoa application?
How can I execute a terminal command (like grep ) from my Objective-C Cocoa
Share
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
You can use
NSTask. Here’s an example that would run ‘/usr/bin/grep foo bar.txt‘.NSPipeandNSFileHandleare used to redirect the standard output of the task.For more detailed information on interacting with the operating system from within your Objective-C application, you can see this document on Apple’s Development Center: Interacting with the Operating System.
Edit: Included fix for NSLog problem
If you are using NSTask to run a command-line utility via bash, then you need to include this magic line to keep NSLog working:
An explanation is here: https://web.archive.org/web/20141121094204/https://cocoadev.com/HowToPipeCommandsWithNSTask