Variables & Scope
Bash variables are fundamental to scripting, allowing dynamic data storage and manipulation. Understanding how to declare variables and manage their scope is critical for writing robust, maintainable scripts. Variables in Bash are untyped and assigned using the = operator, but their scope—global or local—determines where they can be accessed. Proper scoping prevents unintended side effects and namespace pollution, especially in complex scripts.
Declaration Basics¶
Variables are declared by assigning a value using the = operator. No spaces are allowed around the equals sign. By default, all variables are global, meaning they are accessible throughout the entire script and any functions.
Syntax¶
Examples¶
# Simple assignment
count=0
message="Hello, World!"
# Using variables in commands
echo "Current count: $count"
Naming Conventions¶
- Use lowercase or mixed case (e.g.,
user_name). - Avoid uppercase unless the variable is intended to be an environment variable (e.g.,
API_KEY). - Variables are case-sensitive:
USER≠user.
Scope: Global vs Local¶
Bash variables are global by default, but you can limit their scope using the local keyword within functions. Local variables are only accessible within the function they’re declared in, preventing unintended interactions with other parts of the script.
Global Variables¶
# Global variable
global_var="I am global"
my_function() {
echo "Inside function: $global_var"
}
my_function
echo "Outside function: $global_var"
Output:
Local Variables¶
my_function() {
local local_var="I am local"
echo "Inside function: $local_var"
}
my_function
echo "Outside function: $local
Output:
Attempting to access local_var outside the function results in an empty string or error, depending on context.
Best Practices¶
- Prefer
localin functions to avoid polluting the global namespace. - Use uppercase for environment variables (e.g.,
MAX_RETRIES=5) to distinguish them from script variables. - Avoid global variables in large scripts unless necessary; they can lead to hard-to-debug conflicts.
- Always quote variables when using them in commands to prevent word splitting and globbing:
echo "Value: $var".
Key takeaways¶
- Variables are untyped and assigned with
=, with no spaces allowed. - Global variables are accessible throughout the script, while
localrestricts scope to functions. - Use
localinside functions to prevent unintended side effects. - Follow naming conventions (e.g., uppercase for environment variables) for clarity.
- Prefer local variables in larger scripts to maintain clean, modular code.