Is there a way to get the script directory from inside a Mathematica script?

I want a function analogue to NotebookDirectory[] (which doesn't work for scripts). Is there a way to do this?


1 Answer 1

DirectoryName @ $InputFileName

is the answer, right?

And this will work whether you call it from a package or a notebook interface:

parentPath = $InputFileName /. "" :> NotebookFileName[]
parentDir = DirectoryName @ parentPath


path = FileNameJoin[{$TemporaryDirectory, "test.m"}];

 "Print @ DirectoryName @ $InputFileName",

Get @ path


  • $\begingroup$ sorry, but this doesn't work if you call your script (.m) from within the terminal using wolframscript $\endgroup$
    – Santiago
    Aug 22, 2017 at 13:31
  • $\begingroup$ @Santi could you elaborate, with a script.m file containing only: Print["test parent dir: ", DirectoryName @ $InputFileName] I get: i.stack.imgur.com/SrLrA.png $\endgroup$
    – Kuba
    Aug 22, 2017 at 13:41
  • $\begingroup$ hi @Kuba, ok, you are right, but in the way I was running my scripts it doesn't work. If I do: wolfram -script script.m it works. But if I do wolframscript -file script.m it doesn't work. I am on Mathematica 11.1.1 Kernel for Linux x86 (64-bit). $\endgroup$
    – Santiago
    Aug 22, 2017 at 14:29
  • $\begingroup$ do you have an idea why this doesn't work with wolframscript ? $\endgroup$
    – Santiago
    Aug 23, 2017 at 8:31
  • $\begingroup$ @Santi I didn't work with scripts yet so I don't know, I will try to investigate if I find time. You could ask a question on main about that. Just make sure to prepare simple example people can run. $\endgroup$
    – Kuba
    Aug 23, 2017 at 8:33

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.