# Determine how Mathematica was started

I have a notebook that I also execute as a m file on the command line. Depending on whether I run the notebook or the m file, I want to use slightly different commands. For example, NotebookDirectory[] in the nb file should be replaced by Directory[] in the m file. Is there a way to read out how Mathematica was started (on the command line or as a notebook) so that I can use the same file to handle the two different situations?

Other solutions are welcome.

## 1 Answer

This question is more complicated that you might expect.

Things you can check:

• Given how you want to use this, the simplest thing may be to just check if NotebookDirectory[] is different from $Failed. • The documentation would suggest$Notebooks, but be careful: this is True even if running in command line mode but connecting to a front end anyway, e.g. UsingFrontEnd[$Notebooks] will be True. For practical purposes it may work well. • There is$ParentLink. It is set to something else than Null when the kernel is being used through a MathLink connection, which includes the cases when there is a front end present, but may also include other scenarios when the kernel is used through MathLink. I checked that with MathematicaScript, $ParentLink is still Null (even though AFAIK MathematicaScript uses MathLink to invoke the kernel (??)). • There is$ScriptCommandLine, which will be non-empty when using MathematicaScript (but not when invoking the kernel from the command line in other ways).

• There is $BatchInput (look it up). •$InputFileName will be set when reading an .m file using Get. This may be the most robust solution.

• To check that $ParentLink is the usual FE, one can use MathLink`NotebookFrontEndLinkQ[$ParentLink] – Oleksandr R. May 9 '16 at 15:41