0
0
Bash Scriptingscripting~3 mins

Environment variables vs local variables in Bash Scripting - When to Use Which

Choose your learning style9 modes available
The Big Idea

What if you could change a password once and have every script know it instantly?

The Scenario

Imagine you write a script that needs to use a username and password in many places. You type them again and again inside each part of the script or in every new script you create.

The Problem

This manual way is slow and risky. If you mistype the username or password somewhere, your script breaks. Also, if you want to change the username, you must find and update every spot manually. It's easy to forget one and cause errors.

The Solution

Using environment variables lets you store values once and share them across scripts and commands automatically. Local variables keep data inside a script or function safely. This way, you avoid repeating data and reduce mistakes.

Before vs After
Before
username="user1"
password="pass1"
echo $username
# repeated in many scripts
After
export USERNAME="user1"
export PASSWORD="pass1"
echo $USERNAME
# accessible in all scripts
What It Enables

You can easily share important data across scripts or keep it private inside functions, making your automation smarter and safer.

Real Life Example

When deploying a website, you set database login info as environment variables once. All deployment scripts use these variables without rewriting sensitive info everywhere.

Key Takeaways

Local variables store data inside a script or function only.

Environment variables share data across scripts and processes.

Using them reduces errors and saves time updating repeated info.