0
0
Bash Scriptingscripting~15 mins

Subshells (command grouping) in Bash Scripting - Mini Project: Build & Apply

Choose your learning style9 modes available
Using Subshells for Command Grouping in Bash
📖 Scenario: You are organizing a simple bash script to manage files in a folder. You want to group commands together so they run in a subshell, keeping your main shell environment clean.
🎯 Goal: Build a bash script that creates a directory, changes into it, creates a file, and lists the contents, all inside a subshell.
📋 What You'll Learn
Create a variable called folder with the value test_dir
Create a subshell that runs these commands: mkdir $folder, cd $folder, touch file.txt, and ls
Print the current directory outside the subshell to show it did not change
💡 Why This Matters
🌍 Real World
Grouping commands in subshells helps keep your main shell environment clean and avoids side effects like changing directories permanently.
💼 Career
Many automation scripts use subshells to run grouped commands safely without affecting the main script environment, which is important for reliable system administration and deployment tasks.
Progress0 / 4 steps
1
Create the folder variable
Create a variable called folder and set it to the string test_dir.
Bash Scripting
Need a hint?

Use folder="test_dir" to create the variable.

2
Write a subshell to create and enter the folder
Write a subshell using parentheses ( ) that runs these commands in order: mkdir $folder, cd $folder, touch file.txt, and ls.
Bash Scripting
Need a hint?

Use parentheses to group commands: (mkdir "$folder" && cd "$folder" && touch file.txt && ls).

3
Print the current directory outside the subshell
Add a command to print the current directory using pwd outside the subshell to show it did not change.
Bash Scripting
Need a hint?

Simply add pwd after the subshell to print the current directory.

4
Run the script and observe output
Run the script and observe the output. The subshell should list file.txt, and the pwd command should show your original directory.
Bash Scripting
Need a hint?

The output should show file.txt from the subshell ls command, then your current directory path from pwd.