Running Commands in Subshells

Learn how to run commands in subshells.

Accessing the USER variable

When we run commands in our shell, they execute in the current shell and have access to the shell and environment variables we’ve set. Sometimes, we want to run commands with different variables temporarily or run a series of commands without affecting our current shell. Subshells let us do that. To run a command in a subshell, we wrap it in parentheses:

$ (echo "Hello ${USER}")

The command executes in the subshell and prints out the results. The current shell and environment variables are passed on to the subshell, which is why we can access the USER variable.

su temp
clear
(echo "Hello ${USER}")

Run the complete code on the terminal below for practice.

Get hands-on with 1200+ tech skills courses.