Local variables and environment variables serve different purposes in a shell environment:
Local Variables
- Scope: Local variables are only accessible within the shell session or script where they are defined. They cannot be accessed by child processes.
- Definition: They are defined without the
exportcommand. For example:local_var="This is a local variable" - Usage: Typically used for temporary data storage within scripts.
Environment Variables
- Scope: Environment variables are accessible to all processes running in the current shell session and any child processes.
- Definition: They are defined using the
exportcommand. For example:export MY_VAR="This is an environment variable" - Usage: Commonly used to configure system settings and provide information to applications.
Example
# Local variable
local_var="Hello"
echo $local_var # Outputs: Hello
# Environment variable
export env_var="World"
echo $env_var # Outputs: World
# Child process accessing environment variable
bash -c 'echo $env_var' # Outputs: World
# Child process cannot access local variable
bash -c 'echo $local_var' # Outputs nothing
In summary, local variables are limited to the current shell or script, while environment variables can be accessed by any process spawned from that shell.
