Take the 2-minute tour ×
Mathematica Stack Exchange is a question and answer site for users of Mathematica. It's 100% free, no registration required.

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!"
LOLOL

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
1  
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
1  
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

 
discard

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

Browse other questions tagged or ask your own question.