The Wayback Machine - https://web.archive.org/web/20240622033212/https://www.geeksforgeeks.org/shell-scripting-subshell/
Open In App

Shell Scripting – Subshell

Last Updated : 23 Jan, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Shell scripting is a powerful tool for automating tasks and simplifying the management of systems and applications. One important concept in shell scripting is the use of subshells, which allow you to execute commands within a separate shell environment.

A subshell is a child shell that is spawned by the main shell (also known as the parent shell). It is a separate process with its own set of variables and command history, and it allows you to execute commands and perform operations within a separate environment.

There are several ways to create a subshell in shell scripting. One way is to use the parentheses operator, like this:

( command1 ; command2 ; command3 )
  • This will execute the commands within the parentheses in a subshell. The commands are separated by semicolons, and the subshell will terminate when all commands have completed execution.

Another way to create a subshell is to use the bash command, like this:

bash -c "command1; command2; command3"
  • This will execute the commands within the quotation marks in a subshell created by the bash command.
  • One useful feature of subshells is that they allow you to isolate the effects of certain commands or operations. For example, you can use a subshell to set temporary variables or change directories without affecting the parent shell’s environment.

Using a subshell to set a temporary variable

Here’s an example of using a subshell to set a temporary variable:

# Set a variable in the parent shell
FOO=bar

# Create a subshell and set a different value for the same variable
( FOO=baz ; echo $FOO )

# The value of FOO in the parent shell is unchanged
echo $FOO

 

The output of this script would be:

baz
bar

 

As you can see, the value of the FOO variable is set to baz within the subshell, but the value in the parent shell remains unchanged.

Change directories without affecting the parent shell’s current directory

Another example of using a subshell is to change directories without affecting the parent shell’s current directory.

# Show the current directory in the parent shell

pwd



# Create a subshell and change to a different directory

( cd /tmp ; pwd )



# The current directory in the parent shell is unchanged

pwd

 

The output of this script would be:

/home/user
/tmp
/home/user

 

As you can see, the subshell changes to the /tmp directory, but the parent shell’s current directory remains unchanged.

There are many other uses for subshells in shell scripting, including executing commands in the background, creating subshells with modified environments, and more. With the ability to execute commands in a separate shell environment, subshells provide a powerful tool for managing systems and automating tasks in shell scripts.

Full Shell Script- subshell:

#!/bin/bash

# This line sets the variable 'filename' to the first argument passed to the script
filename=$1

# This line prints the hostname of the current system
echo "Hostname: $(hostname)"

# This line creates a subshell and runs the 'ls' command inside it.
# The output of the 'ls' command is then stored in the 'ls_output' variable
ls_output=$(ls)

# This line prints the output of the 'ls' command
echo "Output of 'ls' command: $ls_output"

# This line checks if the file specified by the 'filename' variable exists
# and is a regular file (not a directory). If the file exists, it prints the contents
# of the file using the 'cat' command. If the file does not exist, it prints an error message
if [ -f "$filename" ]; then

  cat "$filename"

else

  echo "Error: File not found"

fi

# This line prints the current working directory
echo "Current working directory: $(pwd)"

# This line prints the current user's home directory
echo "Home directory: $HOME"

 

Here is an example output of the script, given a file named “test.txt” that exists in the current directory and contains the text “Hello, World!”:

Hostname: myhostname
Output of 'ls' command: bashscriptname.sh
test.txt
Hello, World!
Current working directory: /home/user/documents
Home directory: /home/user

 

If the file “test.txt” did not exist in the current directory, the output would be:

Hostname: myhostname
Output of 'ls' command: example.sh
Error: File not found
Current working directory: /home/user/documents
Home directory: /home/user

 

Conclusion

In conclusion, subshells are an important concept in shell scripting that allows you to execute commands within a separate shell environment. They can be created using the parentheses operator or the bash command, and they provide a way to isolate the effects of certain commands or operations. Subshells can be useful for a variety of purposes, including setting temporary variables, changing directories, executing commands in the background, and more. By understanding how to use subshells in your shell scripts, you can greatly improve your ability to automate tasks and manage systems efficiently.


Similar Reads

Shell Scripting - Difference between Korn Shell and Bash shell
Korn Shell: Korn Shell or KSH was developed by a person named David Korn, which attempts to integrate the features of other shells like C shell, Bourne Shell, etc. Korn Shell allows developers to generate and create new shell commands whenever it is required. Korn shell was developed a long year back as it is older than the BASH shell and it has fe
3 min read
Shell Scripting - Restricted Shell
Shell is one of the most important and powerful tools available in GNU/Linux-based systems. One can control the entire system if used correctly, this exact feature makes the shell a double-edged sword. It can potentially harm the system if one executes a system command without knowing its underlying details and consequences. To prevent this we use
5 min read
Shell Scripting - Interactive and Non-Interactive Shell
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Default Shell Variable Value
A shell gives us an interface to the Unix system. While using an operating system, we indirectly interact with the shell. On Linux distribution systems, each time we use a terminal, we interact with the shell. The job of the shell is to interpret or analyze the Unix commands given by users. A shell accepts commands from the user and transforms them
3 min read
Shell Scripting - Shell Signals Values
Prerequisites: Processes, Bash Scripting, Shell Function Library Signals help the operating system to communicate with processes and vice-versa. Signals are also generated when processes don't function properly or try to access prohibited memory. Different signals are mapped to different numbers which are referred to as signal values. The Linux OS
6 min read
Introduction to Linux Shell and Shell Scripting
If we are using any major operating system, we are indirectly interacting with the shell. While running Ubuntu, Linux Mint, or any other Linux distribution, we are interacting with the shell by using the terminal. In this article we will discuss Linux shells and shell scripting so before understanding shell scripting we have to get familiar with th
7 min read
Shell Scripting - Shell Variables
A shell variable is a character string in a shell that stores some value. It could be an integer, filename, string, or some shell command itself. Basically, it is a pointer to the actual data stored in memory. We have a few rules that have to be followed while writing variables in the script (which will be discussed in the article). Overall knowing
6 min read
Shell Script to Show the Difference Between echo “$SHELL” and echo ‘$SHELL’
In shell scripting and Linux, the echo command is used to display text on the terminal or console. When used with the $SHELL variable, which contains the path of the current user's shell program, the output of the echo command can be different depending on whether the variable is enclosed in single or double quotes. echo "$SHELL" will expand the $S
4 min read
Bash Scripting - How to Run Bash Scripting in Terminal
In this article, we are going to see how to run bash script in terminal. For example, we create a bash file set of instructions or commands ( known as bash script ), and through command, we can run this file in terminal. Let see how to run bash script in terminal. Example 1 : In this example we print or echo some text on screen with the help of a t
2 min read
Bash Scripting - Working of Bash Scripting
Bash Scripting is a crucial component of Linux's process automation. You can write a series of commands in a file and then execute them using scripting. A Bash script is a plain text file with a set of commands inside of it. These commands are a combination of ones we typically type on the command line ourselves (like ls or cp, for instance) and ot
6 min read