Bash Variable Basics
Introduction to Variables in Shell Scripting
In bash scripting, variables are fundamental storage units that allow programmers to store and manipulate data dynamically. Understanding variable basics is crucial for effective shell programming on Linux systems.
Variable Declaration and Naming Conventions
In bash, variables are declared without spaces and can contain letters, numbers, and underscores. Here are key rules for variable declaration:
## Valid variable names
name="John"
user_age=30
SYSTEM_PATH="/usr/local/bin"
## Invalid variable names
2name="Invalid" ## Cannot start with number
user-age=25 ## Hyphens not allowed
Types of Variables in Bash
Bash primarily supports two types of variables:
Variable Type |
Description |
Example |
Local Variables |
Accessible only in current shell |
local_var="local" |
Environment Variables |
Available system-wide |
PATH="/usr/bin:$PATH" |
Variable Assignment and Retrieval
## Simple assignment
name="Linux User"
## Retrieving variable value
echo $name ## Outputs: Linux User
echo "${name}" ## Alternative syntax
Scope and Lifetime of Variables
flowchart TD
A[Variable Declaration] --> B{Scope}
B --> |Local| C[Limited to Current Shell/Script]
B --> |Environment| D[Available System-wide]
Dynamic Variable Manipulation
## Concatenation
greeting="Hello, $name"
## Length of variable
echo ${#name} ## Outputs length of variable
## Default values
default_value=${undefined_var:-"Default"}
These foundational concepts in bash scripting provide a solid starting point for understanding variable management in shell programming.