Introduction
Environment variables store information for the system and other programs, while local variables store data only inside a script or shell session.
local local_variable=value export ENV_VARIABLE=value
name="Alice"
echo $nameexport PATH="/usr/local/bin:$PATH"
echo $PATHlocal_var="hello" export ENV_VAR="world" echo $local_var echo $ENV_VAR
#!/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"'
export and are inherited by child processes.local declares a variable limited to that function.export makes variables environment variables, setlocal is not a Bash command, and VAR=value without local is global or inherited.local inside functions for local variables [OK]VAR=hello
function test_func() {
local VAR=world
echo $VAR
}
test_func
echo $VARecho $VAR inside prints 'world'.echo $VAR after function call prints 'hello'.export VAR=hello
function test() {
VAR=world
local VAR
echo $VAR
}
test
echo $VARlocal VAR must appear before assigning a value to VAR inside the function to make it local.echo $VAR prints empty.PATH_VAR inside a function and have it available outside the function and in any child processes. Which is the correct approach?local limits it to the function scope, so it won't be available outside or to child processes.local inside the function, then use export PATH_VAR inside the function to make it environment variable accessible outside and to child processes.Pass the test and this pattern moves unknown