Bash Variables
Storing and using data in Bash scripts
📦 What are Bash Variables?
Variables in Bash are containers that store data values like text, numbers, or command results. They allow scripts to remember information, perform calculations, and create dynamic behavior by referencing stored values throughout your code.
# Create a variable
name="Alice"
# Use the variable
echo "Hello, $name!"
Key Variable Concepts
Declaration
Create and assign variables
name="John"
Access
Use $ to get variable value
echo $name
Environment
System-wide variables
echo $HOME
Read-only
Constant variables
readonly PI=3.14
🔹 Creating Variables
Create variables by assigning a value with an equals sign, no spaces: name=value. Variable names can contain letters, numbers, and underscores, but must start with a letter or underscore. They are case-sensitive. For example, count=10 or USER_NAME="admin". The value can be a string, number, or the result of command substitution. Variables are fundamental for storing data, configuration, and intermediate results, making scripts dynamic and reusable. Always use meaningful names that indicate the variable's purpose for better code clarity.
#!/bin/bash
# String variables
name="Alice"
greeting="Hello"
# Number variables
age=25
count=100
# Using variables
echo "$greeting, $name!"
echo "Age: $age"
echo "Count: $count"
Output:
Hello, Alice! Age: 25 Count: 100
🔹 Variable Naming Rules
Follow conventions for clear, error-free variable names: start with a letter/underscore, use alphanumerics and underscores only. Avoid spaces, hyphens, or special characters. Use uppercase for environment or global constants (e.g., PATH) and lowercase or mixed case for script-local variables (e.g., fileName). Descriptive names like backup_dir are better than bd. This improves readability and maintainability. While Bash is flexible, adhering to these rules prevents unexpected interpretation by the shell and makes your scripts look professional and consistent with common practices.
Rules and Best Practices:
- Start with letter or underscore - name, _temp, myVar
- Use letters, numbers, underscores - user_name, count2
- Case-sensitive - Name and name are different
- No spaces around = - var="value" not var = "value"
- Use descriptive names - user_count not uc
# Good variable names
user_name="Bob"
total_count=50
_temp_file="/tmp/data"
# Bad variable names (will cause errors)
# 2users="invalid" # Can't start with number
# user-name="error" # Hyphens not allowed
# my var="wrong" # No spaces allowed
🔹 Accessing Variables
Access a variable's value by prefixing its name with a dollar sign: $variable. For clarity and to separate the variable name from surrounding text, use braces: ${variable}. This is essential in expansions like ${var}_suffix. For example, echo "Welcome, $USER" prints the current user. The braces syntax also allows advanced operations like substring extraction or default values (${var:-default}). Proper variable access is key to utilizing stored data in commands, conditions, and output, forming the link between data storage and script logic.
#!/bin/bash
name="Alice"
# Simple access
echo $name
# With curly braces (recommended)
echo ${name}
# Concatenation
echo "User: ${name}_admin"
# In strings
echo "Hello, $name! Welcome back."
Output:
Alice Alice User: Alice_admin Hello, Alice! Welcome back.
🔹 Command Substitution
Command substitution in Bash allows you to capture and use the output of a command directly within your script. By wrapping a command in $(...) or backticks, you can store its result in a variable, making your scripts dynamic and responsive to real-time system data. This technique is essential for automating tasks that depend on current dates, file counts, system information, or command results. For example, current_date=$(date) stores today's date, enabling your script to log events or generate time-stamped reports automatically. Mastering command substitution enhances script flexibility and reduces hard-coded values.
#!/bin/bash
# Store command output in variable
current_date=$(date +%Y-%m-%d)
user_count=$(who | wc -l)
current_dir=$(pwd)
echo "Date: $current_date"
echo "Logged in users: $user_count"
echo "Current directory: $current_dir"
# Use in file names
backup_file="backup_${current_date}.tar.gz"
echo "Backup file: $backup_file"
Output:
Date: 2025-01-10 Logged in users: 3 Current directory: /home/alice Backup file: backup_2025-01-10.tar.gz
🔹 Environment Variables
Environment variables are global system-wide settings accessible to all processes and scripts running on your machine. They store critical configuration data such as user paths ($PATH), home directories ($HOME), shell type ($SHELL), and terminal information. These variables ensure portability and adaptability across different systems and user environments. For instance, using $USER instead of a hard-coded username makes your script work for anyone. Understanding and leveraging environment variables is key to writing robust, maintainable, and system-agnostic Bash scripts.
Common Environment Variables:
- $HOME - User's home directory
- $USER - Current username
- $PATH - Command search paths
- $PWD - Current working directory
- $SHELL - Current shell
#!/bin/bash
# Display environment variables
echo "User: $USER"
echo "Home: $HOME"
echo "Shell: $SHELL"
echo "Path: $PATH"
# Create custom environment variable
export MY_VAR="Hello"
echo $MY_VAR
Output:
User: alice Home: /home/alice Shell: /bin/bash Path: /usr/local/bin:/usr/bin:/bin
🔹 Read-only Variables
Read-only variables in Bash act as constants, preventing accidental modification of critical values after their initial assignment. Declared with the readonly keyword or declare -r, these variables protect important configuration data, script settings, or fixed parameters from being altered during execution. For example, readonly MAX_USERS=100 ensures the user limit stays consistent. Attempting to change a read-only variable results in an error, safeguarding your script's integrity. This practice is essential for defining immutable values like version numbers, API endpoints, or security tokens.
#!/bin/bash
# Create read-only variable
readonly PI=3.14159
readonly APP_NAME="MyApp"
echo "PI: $PI"
echo "App: $APP_NAME"
# This will cause an error
# PI=3.14 # Error: PI: readonly variable
Output:
PI: 3.14159 App: MyApp
🔹 Special Variables
Bash provides a set of built-in special variables that offer immediate access to script and system metadata without explicit declaration. These include $0 for the script name, $1-$9 for positional arguments, $? for the exit status of the last command, $$ for the current process ID, and $# for the argument count. They are automatically populated by the shell and are indispensable for handling command-line inputs, debugging, and process control. Using special variables makes scripts more interactive, error-aware, and easier to debug.
Special Variable List:
- $0 - Script name
- $1, $2, ... - Script arguments
- $# - Number of arguments
- $@ - All arguments as separate words
- $? - Exit status of last command
- $$ - Current process ID
#!/bin/bash
# special_vars.sh
echo "Script name: $0"
echo "First arg: $1"
echo "Second arg: $2"
echo "All args: $@"
echo "Arg count: $#"
echo "Process ID: $$"