0
0
Bash Scriptingscripting~5 mins

Environment variables vs local variables in Bash Scripting

Choose your learning style9 modes available
Introduction
Environment variables store information for the system and other programs, while local variables store data only inside a script or shell session.
When you want to share a setting or path with multiple programs, use environment variables.
When you need a temporary value only inside your script, use local variables.
When you want to keep data private to your script and not affect other programs, use local variables.
When you want to configure your shell or programs globally, use environment variables.
When testing or debugging a script, use local variables to avoid changing system settings.
Syntax
Bash Scripting
local local_variable=value
export ENV_VARIABLE=value
Local variables are created by assigning a value without 'export'.
Environment variables are created by using 'export' before the variable.
Examples
Creates a local variable 'name' and prints it.
Bash Scripting
name="Alice"
echo $name
Adds a folder to the environment variable PATH and prints it.
Bash Scripting
export PATH="/usr/local/bin:$PATH"
echo $PATH
Shows both local and environment variables in the same script.
Bash Scripting
local_var="hello"
export ENV_VAR="world"
echo $local_var
echo $ENV_VAR
Sample Program
This script shows the difference: local_var is only inside this script, ENV_VAR is passed to the new shell.
Bash Scripting
#!/bin/bash

# Local variable
local_var="I am local"

# Environment variable
export ENV_VAR="I am environment"

# Print both
 echo "Local variable: $local_var"
 echo "Environment variable: $ENV_VAR"

# Start a new shell to check if variables exist there
bash -c 'echo "Inside new shell - Local: $local_var"; echo "Inside new shell - Env: $ENV_VAR"'
OutputSuccess
Important Notes
Local variables disappear when the script or shell ends.
Environment variables are inherited by child processes but not by parent or sibling processes.
Use 'export' carefully to avoid accidentally changing system-wide settings.
Summary
Local variables exist only inside the current script or shell session.
Environment variables are shared with child processes and other programs.
Use 'export' to make a variable an environment variable.