I have the following code in a .m file which is called test.m:

Export["test.csv",0]; Exit[]

I would like to run this .m file from the command line. I found that I can do that with the command "math -initfile test.m". It seems to work, but when I check out the produced .csv file (it does get produced), I find that it's empty (so does not contain 0). When I run the .m file using the GUI it produces the .csv file with 0.

Anyone know how I can get this working from the command line?


  • 1
    $\begingroup$ I think there was a similar question not long ago where someone tried to import data during initialization: the problem is that some functionality is not yet available during initialization of the kernel, and Import and Export for many formats are among them. This is why using math < tst.m as suggested will usually work. There are even better ways to run mathematica scripts from the command line for newer versions, search the docs (or this site) for mathematica and script to learn more... $\endgroup$ Commented Dec 9, 2014 at 11:43

2 Answers 2


I can reproduce something similar to your issue but I cannot fully understand why. However, if you want an alternative command, that works at least on Windows 7, here is how to do.

Add the mathematica installation folder in the system's path variable. From the command line, move to the folder where the test.m file is saved (I have it in "C:\temp\") and run the following

math < test.m

using -initfile seems to have a different behavior because it asks to me the mathkernel file to run and then generates the empty file test.csv. Differently, using the < it works fine. Moreover, note that using < you don't need to add Exit[] in the code, the kernel automatically exits after the last computation. So, the test.m content is just

Export["test.csv", 0]

I hope this works for you too.

  • $\begingroup$ Wonderful, works perfectly. Thank you $\endgroup$
    – Latrace
    Commented Dec 10, 2014 at 3:47

One possible workaround: It turns out that low level Open/Write i/o works from an initialization file. If the output is something simple like csv you can just roll your own.


ExportString and Import also do not work by the way.


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.