0
0
Bash Scriptingscripting~20 mins

Environment variables vs local variables in Bash Scripting - Hands-On Comparison

Choose your learning style9 modes available
Environment variables vs local variables in Bash scripting
📖 Scenario: You are writing a simple Bash script to understand how environment variables and local variables work differently. This is important when you want to control which variables are visible to other programs or scripts.
🎯 Goal: Learn how to create local variables and environment variables in Bash, and see how they behave differently when running a child script.
📋 What You'll Learn
Create a local variable in a Bash script
Create an environment variable in a Bash script
Write a child script that prints both variables
Observe which variables are accessible in the child script
💡 Why This Matters
🌍 Real World
Understanding environment vs local variables helps when writing scripts that call other scripts or programs, ensuring the right data is shared or kept private.
💼 Career
Many automation and deployment tasks require managing environment variables correctly to configure software and services.
Progress0 / 4 steps
1
Create a Bash script with a local variable
Create a Bash script called parent.sh and inside it, create a local variable called local_var with the value local_value.
Bash Scripting
Need a hint?

Use the syntax variable_name="value" to create a local variable in Bash.

2
Add an environment variable to the script
In parent.sh, add an environment variable called env_var with the value env_value by exporting it.
Bash Scripting
Need a hint?

Use export variable_name="value" to create an environment variable in Bash.

3
Create a child script to print both variables
Create a new Bash script called child.sh that prints the values of local_var and env_var using echo.
Bash Scripting
Need a hint?

Use echo "variable_name=$variable_name" to print variable values in Bash.

4
Run child script from parent and observe output
In parent.sh, add a line to run child.sh after setting the variables. Then run bash parent.sh in the terminal and observe the output.
Bash Scripting
Need a hint?

Use bash ./child.sh to run the child script from the parent script.

Notice that local_var is empty in the child script output because it is local, but env_var is visible because it is exported.