Tom
Tom

Reputation: 169

Run shell commands from a menu bar item

I followed a very helpful guide to create a simple Menu Bar app which has two actions. However, I would like 2 shell commands to be carried out when one of these actions is selected.

The current function in Xcode is:

func constructMenu() {
let menu = NSMenu()

menu.addItem(NSMenuItem(title: "ON", action: #selector(AppDelegate.printQuote(_:)), keyEquivalent: "S"))
menu.addItem(NSMenuItem(title: "OFF", action: #selector(AppDelegate.printQuote(_:)), keyEquivalent: "R"))
menu.addItem(NSMenuItem.separator())
menu.addItem(NSMenuItem(title: "Quit SMAC", action: #selector(NSApplication.terminate(_:)), keyEquivalent: "q"))

statusItem.menu = menu

This shows three options as predicted when I click the menu bar:

Screenshot of the menu bar options

However, this is where my Cocoa knowledge proves insufficient. I would like the following shell scripts to be carried out when I click the ON action:

chmod u+x ~/Desktop/Mask.sh
~/Desktop/Mask.sh

And finally to carry out the following two bash scripts when the OFF button is pressed:

chmod u+x ~/Desktop/Unmask.sh
~/Desktop/Unmask.sh

Upvotes: 2

Views: 897

Answers (1)

l'L'l
l'L'l

Reputation: 47169

The following two classes should be relevant: Process and NSUserUnixTask.

Process
An object representing a subprocess of the current process.
Using the Process class, your program can run another program as a subprocess and can monitor that program’s execution. A Process object creates a separate executable entity; it differs from Thread in that it does not share memory space with the process that creates it.

This would be what you would use to chmod your script for example.

Foundation | Streams, Sockets, and Ports | Process

NSUserUnixTask
An object that executes unix applications.
The NSUserUnixTask class is intended to run unix applications, typically a shell script, from your application. It is intended to execute user-supplied scripts, and will execute them outside of the application's sandbox, if any.

This is what could be used to execute your shell script.

Foundation | Processes and Threads | NSUserUnixTask

Upvotes: 1

Related Questions