Bash Data Types
Understanding data types in Bash scripting
๐ข What are Bash Data Types?
Bash primarily treats all variables as strings, but provides tools to work with different data types including strings, integers, and arrays. Understanding these types helps you manipulate data effectively in your scripts.
# String
name="Alice"
# Integer
age=25
# Array
colors=("red" "green" "blue")
Key Data Type Concepts
Strings
Text data in variables
text="Hello World"
Integers
Numeric calculations
num=$((5 + 3))
Arrays
Multiple values in one variable
arr=(1 2 3)
Associative Arrays
Key-value pairs
declare -A map
๐น Strings
Strings are the fundamental data type in Bash, used for text, filenames, arguments, and command output. They can be defined with single quotes (literal, no expansion), double quotes (allows variable and command substitution), or unquoted (subject to word splitting and globbing). You can concatenate simply by placing them together, get string length with Access array elements individually using their numeric index inside square brackets and curly braces. For example, ${, extract substrings with ${fruits[0]} gets the first element "apple". ${#fruits[@]} returns the number of elements. Use ${!fruits[@]} to get a list of all indices. This syntax allows precise retrieval and measurement of array data, which is fundamental for any script that processes lists of items like filenames, usernames, or configuration values.${str:position:length}, and perform pattern matching and replacement, enabling extensive text processing.
#!/bin/bash
# String creation
name="Alice"
greeting='Hello'
# String concatenation
full_greeting="$greeting, $name!"
echo $full_greeting
# String length
echo "Length: ${#name}"
# Substring extraction
text="Hello World"
echo ${text:0:5} # Output: Hello
# String replacement
echo ${text/World/Bash} # Output: Hello Bash
Output:
Hello, Alice! Length: 5 Hello Hello Bash
๐น Integers and Arithmetic
Although Bash variables are strings, arithmetic expansion $(( )) enables integer calculations. Inside $((expression)), you can use operators for addition (+), subtraction (-), multiplication (*), integer division (/), modulus (%), and exponentiation (** in Bash 4+). It supports parentheses for grouping, increment/decrement operators, and bitwise operations. This allows scripts to perform counters, calculations, and numeric comparisons directly without external tools.
#!/bin/bash
# Integer arithmetic
a=10
b=5
# Basic operations
sum=$((a + b))
diff=$((a - b))
prod=$((a * b))
quot=$((a / b))
mod=$((a % b))
echo "Sum: $sum"
echo "Difference: $diff"
echo "Product: $prod"
echo "Quotient: $quot"
echo "Modulus: $mod"
# Increment/Decrement
count=0
((count++))
echo "Count: $count"
Output:
Sum: 15 Difference: 5 Product: 50 Quotient: 2 Modulus: 0 Count: 1
๐น Arrays
Arrays in Bash allow storing multiple items in one indexed variable. Each element is accessed via numeric indices starting from zero. They're ideal for handling lists like filenames, user entries, or configuration values. Using arrays, you can loop through items efficiently with for loops, sort data, and manage collections dynamically. Arrays reduce the need for multiple separate variables, keeping scripts clean. For example, files=("a.txt" "b.txt") creates an array, and echo ${files[0]} outputs the first item. This structure is essential for batch processing and structured data handling in shell scripts.
#!/bin/bash
# Create array
fruits=("apple" "banana" "cherry" "date")
# Access elements
echo "First: ${fruits[0]}"
echo "Second: ${fruits[1]}"
# All elements
echo "All fruits: ${fruits[@]}"
# Array length
echo "Count: ${#fruits[@]}"
# Add element
fruits+=("elderberry")
echo "Updated: ${fruits[@]}"
# Loop through array
for fruit in "${fruits[@]}"
do
echo "- $fruit"
done
Output:
First: apple Second: banana All fruits: apple banana cherry date Count: 4 Updated: apple banana cherry date elderberry - apple - banana - cherry - date - elderberry
๐น Associative Arrays
Associative arrays use named keys instead of numeric indexes to store values. Declared with declare -A, they function like dictionaries or hash maps. Keys can be strings, enabling intuitive data accessโsuch as user["name"]="John". They're perfect for configurations, lookup tables, or structured datasets. For instance, storing environment settings or user profiles becomes straightforward. Retrieval is efficient: echo ${user["name"]} outputs "John". This makes scripts more readable and maintainable, especially when dealing with complex, named data relationships instead of positional lists.
#!/bin/bash
# Declare associative array
declare -A user
# Assign values
user[name]="Alice"
user[age]=25
user[city]="New York"
# Access values
echo "Name: ${user[name]}"
echo "Age: ${user[age]}"
echo "City: ${user[city]}"
# Get all keys
echo "Keys: ${!user[@]}"
# Get all values
echo "Values: ${user[@]}"
# Loop through associative array
for key in "${!user[@]}"
do
echo "$key: ${user[$key]}"
done
Output:
Name: Alice Age: 25 City: New York Keys: name age city Values: Alice 25 New York name: Alice age: 25 city: New York
๐น Type Declaration
The declare command explicitly defines variable attributes and types in Bash. It enhances control and prevents unintended modifications. Options include -i for integers, -a for arrays, -A for associative arrays, and -r for read-only constants. For example, declare -i count=5 ensures count only holds integers. This improves script robustness, clarity, and error prevention by enforcing data constraints early. Using declare is a best practice for writing predictable, secure, and maintainable shell scripts, especially in larger projects.
Common declare Options:
- -r - Read-only variable (constant)
- -i - Integer variable
- -a - Indexed array
- -A - Associative array
- -x - Export variable (environment)
#!/bin/bash
# Declare integer
declare -i number=10
number=number+5 # Arithmetic without $(())
echo "Number: $number"
# Declare read-only
declare -r PI=3.14159
echo "PI: $PI"
# Declare array
declare -a colors=("red" "green" "blue")
echo "Colors: ${colors[@]}"
# Declare associative array
declare -A config
config[host]="localhost"
config[port]=8080
echo "Host: ${config[host]}"
๐น Type Checking
While Bash is dynamically typed, you can implement checks to validate variable data. Use declare -p to inspect a variable's type or attributes. Conditional tests with -z (empty string) or -n (non-empty) help verify content. For numbers, arithmetic contexts (( ... )) can catch non-numeric values. Though not strict like compiled languages, these methods reduce runtime errors. For example, checking [[ $var =~ ^[0-9]+$ ]] ensures a variable contains only digits before performing calculations.
#!/bin/bash
# Check if variable is a number
is_number() {
[[ $1 =~ ^[0-9]+$ ]]
}
value="123"
if is_number "$value"; then
echo "$value is a number"
else
echo "$value is not a number"
fi
# Check if variable is empty
name=""
if [ -z "$name" ]; then
echo "Name is empty"
fi
# Check if variable is set
if [ -n "$USER" ]; then
echo "USER is set to: $USER"
fi
Output:
123 is a number Name is empty USER is set to: alice