- development
- terminal
- workflow
- turtle-power
Oct 2, 2020 @ 3:42 AM
Overview
Summary
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
Usage
$ (cd ../other-project && npm i)
Example
For this example we will do the following:
- Print the current working directory
- Create the
../project-b
directory. - Change directories to
../project-b
, create a file calledhello.txt
, then writeHello World
to it. - 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.
-
Let's print the current working directory. Enter the following command in your terminal:
$ pwd
The output is the following:
/Development/project-a
-
Create a directory called
project-b
$ mkdir ../project-b
-
Next we will change directories to
project-b
and create a file calledhello.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! -
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
Resources
Sub-shells
- Subshells
- Grouping Commands
- Linux and Unix pwd command tutorial with examples
- How do I run a program with a different working directory from current, from Linux shell?
Commands
Photo
- Photo by Razvan Narcis Ticu on Unsplash