Skip to main content
5 of 6
added notes about older versions, relative pathes and script files
Albert Retey
  • 23.6k
  • 60
  • 104

This is AFAIK not dependent on the OS but how you run Mathematica. If you only run the Kernel in batch mode, it is $Input which you can ask to get a file path of the script just running. It sometimes needs some extra care as it will not always hold the full file name if I remember correctly. I'd start to just print its content in your script and then add/change what's necessary.

As rm-rf has noted there is now (introduced in version 8) $InputFileName which seems to not be affected by the potential problems I mentioned.

In case that anyone needs this for versions before 8, here is a rough sketch of what should work there:

 StringReplace[First[FileNames[$Input, $Path]], 
    "." ~~ "/" | $PathnameSeparator ~~ rest__ :> 
    ToFileName[{Directory[]}, rest]]

to make it reliable you would of course need to check whether $Input is defined at all and whether FindFiles did find the input file at all. This of course assumes that $Path and Directory[] are still the same as when the input file was loaded. There could be additional problems which I now don't remember anymore. Since version 6 there is also an undocumented System`Private`$InputFileName as Leonid has mentioned.

I just realized that even with the current $InputFileName you might not always get a full file path, but could only get a relative path. So my technique to add that if necessary might be useful even with newer versions. For a script file it is not $Path but rather something like GetEnvironment["PATH"] which will contain the information about what's to be added to relative pathes, but the details then will become slightly os dependent. I also think that for script files $InputFileName very well could reliably contain the full path unlike when one uses something like Get["test.m"].

Albert Retey
  • 23.6k
  • 60
  • 104