Use a subshell to run a one-off command in a different directory

By on

A subshell creates a separate instance of the command processor or a subprocess of the parent shell by wrapping a command in parentheses. Any started subshell inherits the parent shell’s working directory, but directory changes do not carry back over to its parent. Because of that, subshells are ideal for running one-off commands in a different directory:

$ pwd
/Users/jeff/conway/
$ (cd www && npm install)
[...]
$ pwd
/Users/jeff/conway/

In this example, the command is run in the www directory[1] but the main shell is in the same place after the command completes.


1. npm has a --prefix flag that allows running the command in another directory. Instead of using a subshell you could also run npm install --prefix www and get the same result.