Bash Data Types
Understanding Bash Data Types
This section introduces the different data types available in Bash scripting.
Strings
Strings are sequences of characters used to store text. They can be manipulated using various string operations such as concatenation and substring extraction.
Example: Strings
# String example
greeting="Hello, World!"
name="Alice"
full_greeting="$greeting, $name!"
echo $full_greeting
Numbers
Numbers in Bash can be used for arithmetic operations. Bash supports integer arithmetic natively, such as addition, subtraction, multiplication, and division.
Example: Numbers
# Number example
num1=5
num2=10
sum=$((num1 + num2))
difference=$((num2 - num1))
product=$((num1 * num2))
quotient=$((num2 / num1))
echo "Sum: $sum, Difference: $difference, Product: $product, Quotient: $quotient"
Arrays
Arrays are used to store multiple values in a single variable. Each element in an array is accessed using an index. You can iterate over arrays and modify elements.
Example: Arrays
# Array example
fruits=("apple" "banana" "cherry")
for fruit in "${fruits[@]}"; do
echo $fruit
done
Associative Arrays
Associative arrays allow you to use named keys to access values. They are similar to dictionaries in other programming languages. You can add or remove keys and values.
Example: Associative Arrays
# Associative array example
declare -A colors
colors[apple]="red"
colors[banana]="yellow"
colors[grape]="purple"
unset colors[banana]
echo ${colors[apple]} # red
echo ${colors[grape]} # purple
Data Type Limitations
Bash does not support floating-point arithmetic natively. For such operations, consider using external tools like bc
or awk
.