I'd like to write command line scripts in Mathematica, but I can't seem to find an Argv[i_Integer]
like function. (The docs are FANTASTIC otherwise.)
Asked
Active
Viewed 2,129 times
6
-
2similar question: [If doing “math foo bar”, how to get foo and bar inside Mathematica?](http://stackoverflow.com/q/7149252/211232) – WReach Nov 01 '11 at 22:29
3 Answers
6
It seems that $ScriptCommandLine is the variable you would need for this, assuming you're using MathematicaScript for scripting. If you use math
or MathKernel -script
it would be $CommandLine.
Other relevant discussions: a rather old one and one in the MMA toolbag.

Community
- 1
- 1

Sjoerd C. de Vries
- 16,122
- 3
- 42
- 94
-
Thanks. Unfortunately, `MathKernel` reports `$ScriptCommandLine` as empty `{}`, no matter the actual arguments supplied. And `MathematicaScript` reports `Could not find Mathematica installation directory.` – mcandre Nov 01 '11 at 21:50
-
-
@mcandre .... and did you see this line in the docs: "The first line of the script must contain the -script option, which must be the **last** option on the line." – Sjoerd C. de Vries Nov 01 '11 at 22:28
-
@mcandre "If no -script option was provided, $ScriptCommandLine gives an empty list." – Sjoerd C. de Vries Nov 01 '11 at 22:44
-
@mcandre This all still assuming you're using MathematicaScript. – Sjoerd C. de Vries Nov 01 '11 at 23:14
-
@mcandre What's the value of $InstallationDirectory when you run Mathematica from the frontend? – Brett Champion Nov 02 '11 at 01:53
-
`$InstallationDirectory` = `"/Applications/Mathematica.app"`, from both `MathKernel -script` and from the Mathematica GUI. – mcandre Nov 02 '11 at 04:50
-
-
@mcandre It seems my assumption you were using MathematicaScript was wrong. In that case you should try `$CommandLine`. – Sjoerd C. de Vries Nov 02 '11 at 09:08
-
-
@yoda Thanks, and now the Mathematica gold badge, that'll impress my kids ;-) – Sjoerd C. de Vries Nov 06 '11 at 19:21
4
$CommandLine
works for Mathematica, MathematicaScript, MathKernel, and math.
args.ma:
#!/usr/bin/env MathKernel -script
Print[$CommandLine]
Example:
$ ./args.ma a b c
{"MathKernel", "-script", "./args.ma", "a", "b", "c"}

mcandre
- 22,868
- 20
- 88
- 147
1
I'm fond of passing things in using environment variables:
http://reference.wolfram.com/mathematica/ref/Environment.html

Joshua Martell
- 7,074
- 2
- 30
- 37
-
Helpful, but it's a bit more manual than specifying command line flags. – mcandre Nov 02 '11 at 04:48