Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

Suppose I write a Mathematica script, called test.m, like the following:

Print["Hello, World!"];
test = ToExpression[$CommandLine[[-1]]];
Print["I'm alive!"];

and then I try to call that script from the command line like so:

math -script test.m a";Print[LOLOL];Quit[]"

I get the following output:

"Hello, World!"

Naturally, this scares me. I'm hoping to have a way to interpret command line arguments in a secure way. Can anyone help?

share|improve this question
Hard to know what to suggest without some idea of what the arguments are and how they will be used. One way to prevent them evaluating is to use e.g. ToExpression[$CommandLine, InputForm, HoldComplete]. – Oleksandr R. Jul 26 '13 at 17:11
Let's say that these arguments are positive integers only. – Kernel Jul 26 '13 at 20:39
In that case, you could use Cases[ToExpression[$CommandLine, InputForm, HoldComplete], HoldComplete[i_Integer] :> i] to safely retrieve a list of only the integers passed on the command line. Or even Flatten@StringCases[$CommandLine, i : (DigitCharacter ..) :> ToExpression[i]]. I'm loath to make this an answer though since this would imply that the question is too localized. Perhaps someone else has a more general approach to suggest. – Oleksandr R. Jul 27 '13 at 0:05
Thanks for the suggestion. I agree it's not really an answer to the question I posed, but it happens to work just fine for my current project. Thanks again! – Kernel Jul 29 '13 at 3:34

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

Browse other questions tagged or ask your own question.