Friday, 22 October 2010

How to open files in Netbeans from Terminal.app (or any CLI) under OS X

Did you ever wondered how to open file from Command Line Interface in Netbeans editor under OS X ? Today i did.

Basically OS X provides powerful command to open Applications or files associated with their default applications:
Help: Open opens files from a shell.
By default, opens each file using the default application for that file.
If the file is in the form of a URL, the file will be opened as a URL.
Options:
-a Opens with the specified application.
-b Opens with the specified application bundle identifier.
-e Opens with TextEdit.
-t Opens with default text editor.
-f Reads input from standard input and opens with TextEdit.
-R, --reveal Selects in the Finder instead of opening.
-W, --wait-apps Blocks until the used applications are closed (even if they were already running).
--args All remaining arguments are passed in argv to the application's main() function instead of opened.
-n, --new Open a new instance of the application even if one is already running.
-g, --background Does not bring the application to the foreground.
-h, --header Searches header file locations for headers matching the given filenames, and opens them.

Unfortunately Netbeans seems to doesn't cooperate well with this command, fallowing command will not work:
open /Applications/NetBeans/NetBeans\ 7.0\ M2.app/ --args --open dummy.rb
Executing it from CLI will open Netbeans but OS X won't pass additional arguments to it . I figured out that I'm still able to run Netbeans directly as binary executable.
/Applications/NetBeans/NetBeans\ 7.0\ M2.app/Contents/MacOS/netbeans --open dummy.rb
This solution isn't perfect, if Netbeans isn't already running, you will have a lot of trash on STDOUT, but if editor is already runnig file will be open but without bringing focus to the editor, you will stay inside Terminal.app window. Solution to this is merge both methods.
open /Applications/NetBeans/NetBeans\ 7.0\ M2.app/ && /Applications/NetBeans/NetBeans\ 7.0\ M2.app/Contents/MacOS/netbeans --open dummy.r

At the end here is simple shell function to simplify the whole process:
function nbopen {
if test -z "$1"
then
echo "usage: nbopen [file]"
else
open /Applications/NetBeans/NetBeans\ 7.0\ M2.app/ && /Applications/NetBeans/NetBeans\ 7.0\ M2.app/Contents/MacOS/netbeans --open $1
fi
}