How can I execute a terminal command (like grep
) from my Objective-C Cocoa application?
Objective-c – Execute a terminal command from a Cocoa app
cocoamacosobjective c
Related Topic
- Ios – Constants in Objective-C
- Ios – How to check for an active Internet connection on iOS or macOS
- Ios – Xcode – How to fix ‘NSUnknownKeyException’, reason: … this class is not key value coding-compliant for the key X” error
- Ios – Passing data between view controllers
- Macos – Open Sublime Text from Terminal in macOS
- Swift – How to call Objective-C code from Swift
- Iphone – Bring up Keyboard for cell in UITableView
- Asp – trigger updatepanel update using
Best Answer
You can use
NSTask
. Here's an example that would run '/usr/bin/grep foo bar.txt
'.NSPipe
andNSFileHandle
are 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