# How to use shell commands inside mathematica

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.

• Is this RunProcess of some help? – user9660 Jun 1 '16 at 7:35
• Why wouldn't you use Directory[]? The current directory of the shell process may in principle not be the same as that of Mathematica. – Szabolcs Jun 1 '16 at 8:17
• @Louis RunProcess won't work. – Boogeyman Jun 1 '16 at 8:31
• @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. – Boogeyman Jun 1 '16 at 8:31
• The RunProcess documentation has multiple examples along this line. Did you read them before deciding that "it won't work"? – Szabolcs Jun 1 '16 at 9:09

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)