Problem Statement
Explain variable scope in bash including local vs global variables, environment variables, and readonly variables.
Explanation
Global variables by default: any variable assigned at top level is accessible throughout script and sub-functions. Example: VAR=value at script level is global. Changes in functions affect global scope unless declared local. This can cause unintended side effects if functions modify global variables.
Local variables declared with 'local' keyword inside functions are only accessible within that function, preventing pollution of global namespace. Example:
```bash
function test() {
local LOCAL_VAR="function scope"
GLOBAL_VAR="modified globally"
}
```
LOCAL_VAR isn't accessible outside function, GLOBAL_VAR modifies global variable or creates it if didn't exist.
Environment variables exported with 'export' are passed to child processes (subshells, executed commands). Example: export PATH=$PATH:/new/path makes PATH available to all subsequent commands. Declare and export together: export VAR=value. Child processes inherit exported variables but changes in child don't affect parent. Check environment: env shows all exported variables, printenv VARNAME shows specific variable.
Readonly variables can't be modified after creation: readonly CONST=value or declare -r CONST=value. Attempting modification causes error. Use for constants like configuration values that shouldn't change. Unset doesn't work on readonly variables. Readonly -p lists all readonly variables.
Special variables: $HOME (home directory), $USER (username), $PWD (current directory), $OLDPWD (previous directory), $PATH (executable search path), $SHELL (default shell), $$ (current process PID), $! (last background process PID). These are typically environment variables set by shell or system.
Best practices: use local for function variables preventing side effects, export only variables needed by child processes, use readonly for true constants, prefix global variables with descriptive names avoiding conflicts, and document variable scope in complex scripts. Understanding scope prevents hard-to-debug issues from variable conflicts.