# Running a shell script within Mathematica

The title pretty much explains it and I have not found something similar already posted. Perhaps I am not searching for the correct title or maybe this is something very basic, but I would appreciate any help!

Is there a way within the Mathematica front-end to run a command line argument into the terminal? I am using bash and Mathematica 9.0.

Thanks!

-
This google groups talk about it :) –  Öskå Apr 11 '14 at 10:31
@Öskå Thanks, Run[] works perfectly! –  someuser_ Apr 11 '14 at 11:09
Without wanting to sound rude myself, I already checked the web and could not find the answer. Moreover, since this group is interested in collecting answers to questions about Mathematica, perhaps it is nevertheless useful to have the question posted here. There seems to be enough space on the web for that. –  someuser_ Apr 11 '14 at 11:11
To be honest, I struggled with getting this to work myself some while ago. I find interaction with external commands to be pretty touchy. Having more, clearer resources on this is in no way a bad thing, I think. –  episanty Apr 11 '14 at 11:23
Relevant or possible duplicate: mathematica.stackexchange.com/questions/6876/… –  Sjoerd C. de Vries Apr 11 '14 at 11:36

The command Run will do exactly that. For example, try

Run["touch ~/Desktop/blankfile"]


If you want to read the results back in, there are a few options, and the choice between them depends on exactly what you want to do.

• The RunThrough command lets you read the output of a command-line back as a Mathematica expression. For example, try

RunThrough["bc", 123 + 456]


579

• The OpenRead command can also run external comands, and returns the output as an InputStream object. This can then be accessed using ReadList and related commands, and allows for some fancier manipulations. For a basic example, try

ReadList[OpenRead["!echo hi"]]


Note, in particular, the use of an exclamation mark at the beginning of the OpenRead argument. In general OpenRead["!command"] is equivalent to typing command into a terminal.

I should also mention that for many of the applications you might want to call - including C, C++, Java, .NET, and MATLAB - there are dedicated interfaces which are overwhelmingly likely to be more useful than a direct call on the terminal. Some of these can be accessed on the Calling External Programs guide; to communicate with MATLAB you should use MATLink.

Edit: it seems Mathematica v10 has expanded capabilities for starting, controlling, and talking to external processes. For more information, see Direct Control of External Processes in the documentation.

-
Exactly what i need, thanks! –  someuser_ Apr 11 '14 at 11:12
If your external script is actually MATLAB then I would strongly urge you to use MATLink. –  episanty Apr 11 '14 at 12:37