# Can't save output in the script mode

I encounter the problem that I can't save any output from Mathematica script. Here is a minimal example.

test.m

Export["/home/my_home_folder/file.txt", "hello world"]


I run the script with

math -script test.m


and the output file is not produced. Instead of math I've also tried MathematicaScript and wolframscript -f test.m, they hadn't work either.

Interactively, i.e. running math from the terminal and executing the same Export command, everything works just fine. I run the script remotely using ssh on a Linux machine.

Is there a way to fix this or any alternative way of saving the data from the script mode?

EDIT.

OK, I resolved the problem and it was pretty dumb. I used Mathematica as an editor and my cells was of the "Input" type, but it should have been of the "Code" type, otherwise, it doesn't work.

Here is the non-working version of the code as it is viewed by Notepad:

(* ::Package:: *)

(* ::Input:: *)
(*Export["/home/my_home_folder/file.txt","hello world"]*)


And here is the working one:

(* ::Package:: *)

(* ::Code:: *)
(*Export["/home/my_home_folder/file.txt","hello world"]*)

• Try math -run "<<test.m" Mar 31, 2020 at 21:36
• @MannyC , thanks! It doesn't work though. With this command, an interactive session is opened, as if it was just math Apr 1, 2020 at 8:48
• If you want it to exit later you can do math -run "<<test.m;Quit[]" Apr 1, 2020 at 9:28
• @MannyC OK, I see. The problem is, however, that the output file is still not produced. Interactively everything works, but I'd like to do some scripting and potentially submit a job to a cluster. Apr 1, 2020 at 13:20

This is what I usually do for scripting (this works in a cluster too). Say I want to write script that depends on one argument. Then I define script.m to be

cmds=Drop[\$CommandLine,3];

param = cmds[[1]];

(*Do stuff with param*)
result = param;
path = "/path/to/my/folder/result.txt";
(*End of stuff*)

Export[path, result];
WriteString["stdout", "Results exported to "<>path<>"\n"];

Quit[];


Then if you call it with

math -run "<<script.m" "Write this!"


It will write Write this! to the file /path/to/my/file/result.txt. This works fine for me, even on a cluster. Recall that when a job gets evaluated on a cluster, it's evaluated on a machine different from the login node. So Directory[] will give a different output.

Also, in most clusters you can redirect stdout to some file. In slurm for example you have to set up

#!/bin/bash
#SBATCH --chdir=/path/to/my/folder
#<Possibly other options>
#...

math -run "<<script.m" "Write this!"


But you may have a different cluster manager.

• Thank you for your extended answer! I kept trying and finally resolved the problem. It was really stupid (see the edit). Apr 2, 2020 at 10:40