Bash Variable Basics
Understanding Shell Variables in Bash Scripting
In bash scripting, variables are fundamental containers for storing and manipulating data. They play a crucial role in shell programming, enabling dynamic and flexible script execution.
Variable Declaration and Assignment
In bash, variable declaration and assignment are straightforward:
## Simple variable assignment
name="John Doe"
age=30
is_student=true
## Declaring variables without initial value
declare username
username="admin"
Variable Naming Conventions
Bash has specific rules for variable naming:
Rule |
Example |
Description |
Start with letter/underscore |
_valid, user_name |
Cannot start with numbers |
Case-sensitive |
Name â name |
Bash distinguishes uppercase and lowercase |
No spaces around = |
correct="value" |
Spaces break assignment |
Types of Variables in Bash
graph TD
A[Bash Variables] --> B[Local Variables]
A --> C[Environment Variables]
A --> D[Special Variables]
Code Examples Demonstrating Variable Usage
#!/bin/bash
## Local variable
local_var="I am local"
## Environment variable
export GLOBAL_CONFIG="/etc/myapp/config"
## Reading user input
read -p "Enter your name: " user_name
echo "Hello, $user_name!"
## Arithmetic with variables
x=10
y=5
result=$((x + y))
echo "Sum: $result"
Variable Scope and Visibility
Variables in bash have different scopes:
- Local variables: Available only within the script or function
- Environment variables: Accessible across multiple scripts and processes
- Special variables: Predefined by bash, like
$0
(script name)