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


I saw there are some commands like

Run["!echo $PWD"]

but how to use that inside SetDirectory.

  • $\begingroup$ Is this RunProcess of some help? $\endgroup$
    – user9660
    Jun 1, 2016 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, 2016 at 8:17
  • $\begingroup$ @Louis RunProcess won't work. $\endgroup$
    – BabaYaga
    Jun 1, 2016 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$
    – BabaYaga
    Jun 1, 2016 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, 2016 at 9:09

1 Answer 1


this works for me under linux:


( 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:


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"}]


 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)


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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