← Today I Learned

Commands in a Sub-shell, Turtle Power

Spawn sub-shells so you never leave your current working directory.

  • development
  • terminal
  • workflow
  • turtle-power

Oct 2, 2020 @ 3:42 AM



I was trying to avoid having to change directories to run a command, then switch back to my current working directory. You can run commands in sub-shells by wrapping the commands in parenthesis ().

The parentheses cause a sub-shell to be spawned. After the program exits, the sub-shell terminates, returning you to your prompt of the parent shell, in the directory you started from. | Source


$ (cd ../other-project && npm i)

Thumbs up Abed


For this example we will do the following:

  1. Print the current working directory
  2. Create the ../project-b directory.
  3. Change directories to ../project-b, create a file called hello.txt, then write Hello World to it.
  4. Verify that we successfully wrote to the hello.txt file.

We can execute these commands without actually leaving our current directory by wrapping parenthesis () around the commands. Because... no one want's to keep typing cd ../ all the time. Assume we are located in the /Development/project-a directory.

  1. Let's print the current working directory. Enter the following command in your terminal:

    $ pwd

    The output is the following:

  2. Create a directory called project-b

    $ mkdir ../project-b
  3. Next we will change directories to project-b and create a file called hello.txt. After we create the file we will write "Hello World" to it. Enter the following command (don't forget the parenthesis () around the command 😁):

    $ (cd ../project-b && touch hello.txt && echo "Hello World" > hello.txt)

    Notice we are still in the /Development/project-a directory!

  4. You can display the contents of the hello.txt file with the cat command:

    $ cat ../project-b/hello.txt

    The output is the following:

    Hello World

    Thumbs up Troy





All rights reserved 2023