5
$\begingroup$

I want to know how to use simple shell commands inside mathematica. For example: I want to set the current directory as the NotebookDirectory using shell command PWD. Something like

SetDirectory[$PWD]

I saw there are some commands like

Run["!echo $PWD"]

but how to use that inside SetDirectory.

$\endgroup$
  • $\begingroup$ Is this RunProcess of some help? $\endgroup$ – user9660 Jun 1 '16 at 7:35
  • $\begingroup$ Why wouldn't you use Directory[]? The current directory of the shell process may in principle not be the same as that of Mathematica. $\endgroup$ – Szabolcs Jun 1 '16 at 8:17
  • $\begingroup$ @Louis RunProcess won't work. $\endgroup$ – Boogeyman Jun 1 '16 at 8:31
  • $\begingroup$ @Szabolcs I can use Directory[] but that is not what I want. I want to know how to incorporate the shell (bash) commands into mathematica if it is possible. $\endgroup$ – Boogeyman Jun 1 '16 at 8:31
  • $\begingroup$ The RunProcess documentation has multiple examples along this line. Did you read them before deciding that "it won't work"? $\endgroup$ – Szabolcs Jun 1 '16 at 9:09
8
$\begingroup$

this works for me under linux:

 SetDirectory[StringDrop[RunProcess["pwd","StandardOutput"],-1]]

( StringDrop drops a trailing "\n" )

Note the directory returned is the same as returned by Directory[] (even if you change it with SetDirectory ), which tells us RunProcess runs in an environment set up by mathematica.

Edit This:

 SetDirectory[StringDrop[RunProcess[{"printenv","PWD"},"StandardOutput"],-1]]

gives the directory from which I start mathematica if started from a shell prompt. (Even if previously changed by SetDirectory). This directory is also available as $InitialDirectory.

I should add I also messed with this on a windows machine with no luck. On windows Directory[] does not return the startup directory when starting from a command prompt, and RunProcess evidently can not run intrinsic dos shell commands like dir, chdir, etc.

 RunProcess[{"cmd", "/C", "set"}]

or

 RunProcess[$SystemShell, "StandardOutput", "set\nexit\n"]

gets us environment variables, but nothing that looks like the startup directory. $InitialDirectory doesn't report what we want either on windows. (I guess this explains why windows apps always try to "save as" in some random place that you don't want)

$\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.