Variables are like containers that can be used to store data or information
When we start to write complex logic in bash script there will be some data that are need in more than one place or repeating. We can simply use a variable and use it in all the places where we need them.
Bash has two types of variables:
1️⃣ System-Defined Variables
2️⃣ User-Defined Variables
These are predefined variables provided by the shell and system. You can view all system variables using any of the following command in the terminal:
printenvenvset
| Variable | Description |
|---|---|
$HOME |
User's home directory |
$USER |
Logged-in username |
$PATH |
Directories where the system searches for executables |
$SHELL |
The shell currently in use (/bin/bash, /usr/bin/zsh, etc.) |
$PWD |
Current working directory |
$UID |
User ID |
$HOSTNAME |
Name of the computer |
$LANG |
System language setting |
You can use these variables in your bash script. Let's create a bash script and run it.
#!/bin/bash
echo "User Information:"
echo "-----------------"
echo "Username : $USER"
echo "User ID (UID) : $UID"
echo "Home Dir : $HOME"
echo ""
echo "System Information:"
echo "-------------------"
echo "Hostname : $HOSTNAME"
echo "Current Shell : $SHELL"
echo "Current Dir : $PWD"
echo ""
echo "Environment Settings:"
echo "---------------------"
echo "System Language : $LANG"
echo "Executable Paths: $PATH"After running this script you will get a some information about your computer.
These are variables created by the user in scripts or the terminal.
| Type | Description | Example |
|---|---|---|
| Local Variable | Exists only in the current shell/session. | my_var="Hello" |
| Global Variable | Can be accessed by child processes. | export my_var="Hello" |
| Read-Only Variable | Cannot be modified after assignment. | readonly my_var="Hello" |
| Special Variables | Used for script arguments, exit status, etc. | $0, $1, $?, $$ |
As mentioned above variables hold values. So you need a name for the variable and some value to store in it. You can can declare a variable using a name follwed by and equal sign follwed by the value.
Now, to access this variable you should used $ sign follwed by the variable name.
name="Newton"
echo $nameThe variables we used above store string type value. There are other data types supported by Bash.
| Data Type | Description |
|---|---|
| String | Default type; all variables are treated as strings. |
| Integer | Used in arithmetic with $(( )), let, or expr. |
| Float (Decimal) | Not supported natively; use bc or awk for calculations. |
| Array | Indexed lists, e.g., arr=("val1" "val2"). |
| Associative Array | Key-value pairs, requires declare -A arr. |
| Boolean | Simulated using 0 (true) and 1 (false). |
In bash you dont have to define data type at the time of delaration. Bash Variables Are Untyped In Bash, you can assign any type of value to a variable without specifying a type. Bash automatically interprets variables based on usage.
#!/bin/bash
# STRING (Default type)
name="Newton"
echo "String Example: Hello, $name!"
# INTEGER (Used for arithmetic)
num1=10
num2=5
sum=$((num1 + num2)) # Arithmetic operation
echo "Integer Example: Sum of $num1 and $num2 is $sum"
# FLOAT (Decimals using bc)
num3=5.5
num4=2.2
result=$(echo "$num3 + $num4" | bc)
echo "Float Example: Sum of $num3 and $num4 is $result"Don't worry about sum and result variable, there will be explained later.
Bash supports one-dimensional arrays, which can store multiple values in a single variable.
fruits=("Apple" "Banana" "Cherry")Elements are space-separated inside ().
echo "First fruit: ${fruits[0]}"
echo "Second fruit: ${fruits[1]}"Use ${array[index]} to access elements.
echo "All fruits: ${fruits[@]}"
echo "All fruits: ${fruits[*]}"Use @ or * to prints all elements.
echo "Total fruits: ${#fruits[@]}"${#array[@]} gives array length.
fruits+=("Mango")
echo "Updated Fruits: ${fruits[@]}"fruits[1]="Grapes"
echo "After Replacement: ${fruits[@]}"Replaces Banana with Grapes.
unset fruits[1] # Removes the second element
echo "After Deletion: ${fruits[@]}"Use unset to remove an element.
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
doneBash 4.0+ supports associative arrays:
declare -A person
person[name]="Newton"
person[age]=125
echo "Name: ${person[name]}"
echo "Age: ${person[age]}"Use declare -A for key-value pairs.
Create a bash script with the following code and run it.
#!/bin/bash
fruits=("Apple" "Banana" "Cherry")
echo "Fruits: ${fruits[@]}"
fruits+=("Mango")
echo "Updated Fruits: ${fruits[@]}"
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done