6

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.

J. M.'s missing motivation
  • 124,525
  • 11
  • 401
  • 574
BabaYaga
  • 1,836
  • 9
  • 19

1 Answers1

9

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)

george2079
  • 38,913
  • 1
  • 43
  • 110