15
$\begingroup$

At UNIX command line, one can run ls -la $HOME. How to trigger this from Mathematica notebooks?

Run["!ls -la $HOME"]
32512

Returns some integer -- what is it? -- but not the normal output.

$\endgroup$
1
  • 1
    $\begingroup$ See this answer by Mike Honeychurch for a way to create a cell that evaluates Unix commands. $\endgroup$
    – Michael E2
    Oct 19, 2014 at 3:06

4 Answers 4

22
$\begingroup$

The Run command returns the exit code of the program being run. In your case, the program is "!ls" which probably doesn't exist on your system (If you try

sh -c '!ls -la $HOME'

you'll also get an error). Why it returns 32512 instead of 127 (which is the return value I get by the shell) I don't know; however I notice that $32512 =127\cdot 256$, so I guess it's in order to better distinguish valid exit codes (usually telling about errors during the execution) from errors occurring when trying to execute the command (like not finding the executable).

If you start a raw kernel and type

Run["ls -la $HOME"]

(without exclamation mark) you'll see the output of the ls command on standard output, and a returned value of 0 (the exit code of ls). If you do it from a notebook, the standard out will be the one Mathematica was started with; if started from a terminal, that's where the output will happen, otherwise it will end up elsewhere or even nowhere (in my test, the directory listing ended up in .xsession-errors because I started Mathematica through the desktop environment).

If you are interested in the actual output, you have to use a file reading command, and use the special "!" syntax; for example Import as suggested by user18792,

Import["!ls -la $HOME", "Text"]

giving you all the output in a single string, or ReadList as suggested by Gustavo Delfino,

ReadList["!ls -la",String]

giving you a list of strings, each containing a single line of the output.

Note that the exclamation mark says you want to get the output of a command instead of the contents of a file (whose name would have gone at that point otherwise). That's why you don't put the exclamation mark at the Run command: Its argument is not a file to read, but already a command to execute, thus you don't need (and cannot use) the exclamation mark "escape" to use a command instead of a file.

If you need both the output and the exit code, apparently in version 10 you can use RunProcess (I can't check that because I don't have access to v10). From the documentation, I get that the command would look like the following:

RunProcess[{"ls", "-la", Environment["HOME"]}]
$\endgroup$
3
  • $\begingroup$ Did not know about this new RunProcess. Your example works well. There is also a new interesting StartProcess function in v10, to run or interact with background tasks ("without blocking the Wolfram Engine")... $\endgroup$
    – SquareOne
    Oct 15, 2014 at 9:09
  • 1
    $\begingroup$ The UNIX system call that waits for an external process to finish running (appropriately called wait()) actually yields a value that is the process's exit code shifted left by 8 bits, assuming the process exited normally. Normally you never see this value, because most programs (including a shell) reverse the leftward bit shift, but I guess Mathematica doesn't (whether to provide complete information about the exit status, or just because of a bug, I don't know). That's probably why you get 32512. $\endgroup$
    – David Z
    Oct 15, 2014 at 18:39
  • $\begingroup$ @DavidZ: Thank you for that information. I just checked with Run["false"] and I indeed got 256 instead of 1, providing further evidence for this hypothesis. $\endgroup$
    – celtschk
    Oct 15, 2014 at 18:49
8
$\begingroup$
Import["!`echo ls -la $HOME`", "Text"]
$\endgroup$
7
$\begingroup$

"Run" does not return the output of the command. On windows I can do ReadList["!dir", String] and it returns the expected output. I am pretty sure that ReadList["!ls -la", String] will work. I am not too sure about the environmental variable $HOME, buy you can give it a try.

For more information see http://reference.wolfram.com/language/tutorial/ExternalPrograms.html

$\endgroup$
4
$\begingroup$
RunProcess[$SystemShell, "StandardOutput", "ls -la $HOME"]

My original answer is now somewhat obsolete with the above having been jogged by george2079's comments. To modify and provide a slightly shorter invocation that also allows the loading of a shell initialization file.


Options[myRunProcess] := {"FileToSource" -> None};

myRunProcess[process_, prop_?AtomQ, OptionsPattern[]] := Let[
   sfr = OptionValue["FileToSource"],
   sf = If[sfr === None, "", "source " <> sfr <> "\n"],
   tf = sf <> process <> "\nexit\n",
   RunProcess[$SystemShell, prop, tf]
   ];

myRunProcess[process_, opt___Rule] := myRunProcess[process, "StandardOutput", opt]

and then:

myRunProcess["ls -la $HOME"]
myRunProcess["ls -la $HOME","FileToSource" -> FileNameJoin[{$HomeDirectory, ".profile"}]]
myRunProcess["ls -la $HOME","ExitCode"]

etc.

$\endgroup$
5
  • $\begingroup$ RunProcess[{"comm", "-f"}, All, "arg"] is not equivalent to "comm -f arg", the third argument to RunProcess is passed as input. (of course for some example the result might be the same). You can actually just do RunProcess[StringSplit["comm -f arg1 arg2"]] $\endgroup$
    – george2079
    Dec 29, 2016 at 21:35
  • $\begingroup$ @george2079 Ok, can you give a minimal example to illustrate this non-equivalence - thanks. The second equivalence though doesn't hold RunProcess[StringSplit["comm -f arg1 arg2"]] often doesn't produce the same as a terminal "comm -f arg1 arg2" - as. the "ssh" example illustrates. $\endgroup$ Dec 29, 2016 at 21:48
  • $\begingroup$ yea, the embedded single quotes mess up StringSplit. The example from the docs RunProcess["echo",All,"hello world"] returns nothing, not the same as "echo hello world". (I must be that way, at least on linux there really is no distinction between flags and arguments at the shell level ) $\endgroup$
    – george2079
    Dec 29, 2016 at 22:02
  • $\begingroup$ Indeed, yes RunProcess' first arguments contains flags and arguments but not standard input as per docs. In this case RunProcess[{"echo", "hello world"}, "StandardOutput"] is equivalent to "echo hello world" but then also from the docs is also equivalent to RunProcess[$SystemShell, "StandardOutput", "echo hello world exit "] but I guess this proves my point, or at least proves why I need myRunProcess :) - rather than having to interpret flags/arguments/inputs just enter myRunProcess["echo hello world"] $\endgroup$ Dec 29, 2016 at 23:19
  • $\begingroup$ Actually following on, it seems therefore that RunProcess already has scope for the sought-after shell replication - perhaps this is the point of its third argument i.e. just use RunProcess[$SystemShell, "StandardOutput", "comm"]? $\endgroup$ Dec 29, 2016 at 23:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.