
Understanding Variables in Bash
In Bash scripting, variables are like storage containers for data. Whether you want to store a username, a filename, a command result, or any kind of information — variables make your scripts dynamic and powerful.
Learning how to define, use, and manipulate variables is essential for writing clean, reusable, and functional Bash scripts.
What is a variable in bash ?
A variable in Bash is a named space in memory that stores a value. You can assign a value to a variable and reference it later in your script.
Think of a variable as a shortcut to some information.
How to Define a Variable
Here’s the basic syntax:
variable_name=value
Important: No spaces on either side of the equal sign =.
Example:
name=“Hacklivly”
To access the value stored in a variable, prefix it with a $:
echo $name
Output:
Hacklivly
Common Examples
Store a string:
greeting=“Welcome to Bash scripting!”
echo $greeting
Store a number:
count=5
echo “There are $count users.”
Use in arithmetic:
a=10
b=20
sum=$((a + b))
echo “Sum is $sum”
Use Cases of Variables in Bash Scripts
- Dynamic script behavior (change one value, affects whole script)
- Storing user input
- Temporarily hold command output
- Creating configuration flags
- Reusing file paths or command options
Reading User Input into a Variable
You can ask the user for input and store it in a variable:
echo “What is your name?”
read username
echo “Hello, $username!”
read takes input from the user and stores it in the variable.
Special Variables in Bash
Variable Description
$0 - Name of the script
$1 to $9 - Arguments passed to script
$# - Number of arguments
$@ - All arguments
$$ - Process ID of the script
$? - Exit status of last command
Example:
echo “Script name: $0”
echo “First argument: $1”
Command Substitution in Variables
You can store the output of a command in a variable using command substitution:
current_date=$(date)
echo “Today is: $current_date”
Best Practices
Use meaningful variable names (filename, user_input, backup_dir)
Use quotes to avoid word splitting or globbing :
message=“Welcome to Hacklivly”
echo “$message”
Use lowercase variable names for script-specific variables.
Always initialize variables before use.
Variable Types in Bash
Bash treats all variables as strings by default, but you can use them for arithmetic too.
For structured data:
Arrays → my_array=(one two three)
Associative arrays → Bash 4+ (declare -A)
Exporting Variables (Environment Variables)
If you want a variable to be available to child processes, you must export it:
export PATH=“$PATH:/opt/myapp/bin”
You can now access $PATH even in scripts or subshells.
Why Variables Are Important in Bash
- Reusability – Define once, use many times.
- Dynamic Behavior – Change flow or content based on variable values.
- Simplification – Make complex scripts easier to understand.
- Interactivity – Capture input, generate output dynamically.
- Automation – Use system values, filenames, user choices.