4
$\begingroup$

Is it possible to run a complex terminal command and retrieve its output. I understand that RunProcess could do this but it cannot directly execute full command and it seems rather complex to rewrite things in a way that RunProcess can run them. For example if I want to run the simple command

"ls -tr | tail -1"

and retrieve the output how can I achieve this?

$\endgroup$
7
$\begingroup$

If you prepend bash -c to your RunProcess command, you can pass ls -ltr | tail -1 as a single argument (at least with v12 on Windows 7 with cygwin or Windows 10 with the subsystem for linux).

RunProcess[{"bash", "-c", "ls -ltr | tail -1"}, "StandardOutput"]
$\endgroup$
  • $\begingroup$ Great! That easily beats my own solution! $\endgroup$ – Kvothe Sep 6 at 8:11
  • $\begingroup$ Works on: Ubuntu 18 too. $\endgroup$ – Kvothe Sep 6 at 8:46
2
$\begingroup$

One way is to write away the standard output to a file using the shell redirect "> file" to create a temporary file and read from there.

run[command_String]:=Module[{out},
 Run[command<>" > tmpstout.txt"];
 out=Import["tmpstout.txt","Text"];
 DeleteFile["tmpstout.txt"]; out]

Works for this for example.


Ironically the temporary file will first be created so for the command above it will be the file returned. Which is technically correct, (the best kind of correct) but might not be as intended.


This solutions is only a sketch and you have to be careful with the location of the temporay file (so that it is in the directory you are importing from). Anyway, don't use it since the accepted solution is much better.

$\endgroup$

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.