msmialko
msmialko

Reputation: 1619

How to ask Cocoa app to run an action from the terminal and then return the result

My Cocoa MacOS app has an action that modifies some files in the disk. I want to make that actions available to run from a terminal.

For example, if I run:

$ echo `myApp runAction`

that would open the app, execute some code associated with "runAction", and then print a result to the console.

Unfortunately, I can't just make a Command Line Tool because of its limitations (can't include dynamic frameworks).

Any tips how to make it?

Upvotes: 1

Views: 279

Answers (2)

pointum
pointum

Reputation: 3177

Even if your application is an .app bundle, its executable is still the same kind of binary file that you would get in a Command Line Tool.

You can execute it in Terminal, pass arguments, print output. E.g.

$ ./MyApplication.app/Contents/MacOS/MyApplication --some-argument

Depending on what your app is for, it might be not perfect solution, but it’s a completely valid way to use it.

Upvotes: 1

Robert
Robert

Reputation: 160

You should make your app scriptable with Apple Script. With this you "speak" to your app in bash (or zsh) no matter if it is running or not by :

osascript -e 'tell app "myApp" to runAction'

or by an AppleScript script written in the Script Editor app.

When app is not running it will launch first.

There are a few examples/documentations in the web which are sufficient for basic tasks like executing a command and returning the result:

Mac Scripter link

Making A Mac App Scriptable Tutorial (raywenderlich.com) link

In my case these docs were not sufficient for complicated tasks like passing parameters to the command, but for simple tasks like:

osascript -e 'tell app "myApp" to login'

osascript -e 'tell app "myApp" to logout'

— and myApp returns a literal "0" or "1" if the action failed for some reason or was successful —

it worked. And osascript -e 'tell app "myApp" to quit' even came for free.

Regards, Robert

Upvotes: 3

Related Questions