Bash
Arrays
Bash array operations.
By EZ4Code Team
basharray
Code
#!/bin/bash
# Declare array
fruits=("apple" "banana" "cherry")
nums=(1 2 3 4 5)
# Associative array (requires bash 4+)
declare -A ages
ages["Alice"]=30
ages["Bob"]=25
# Access element
echo ${fruits[0]} # apple
echo ${fruits[-1]} # cherry (last element)
echo ${ages["Alice"]} # 30
# All elements
echo ${fruits[@]} # apple banana cherry
echo ${fruits[*]} # apple banana cherry
echo ${!fruits[@]} # 0 1 2 (indices)
echo ${!ages[@]} # Alice Bob (keys)
# Array length
echo ${#fruits[@]} # 3
echo ${#fruits[0]} # 5 (first element length)
# Add element
fruits+=("date" "elderberry")
# Modify element
fruits[0]="apricot"
# Delete element
unset fruits[1] # Delete index 1
unset fruits # Delete entire array
# Slice
echo ${fruits[@]:1:2} # Take 2 from index 1
# Iterate
for fruit in "${fruits[@]}"; do
echo "Fruit: $fruit"
done
# Iterate associative array
for key in "${!ages[@]}"; do
echo "$key is ${ages[$key]}"
done
# Create array from string
str="a,b,c,d"
IFS=',' read -ra arr <<< "$str"
echo ${arr[2]} # c
# Sort
sorted=($(printf '%s\n' "${fruits[@]}" | sort))
echo ${sorted[@]}Explanation
Bash supports indexed and associative arrays; ${arr[@]} gets all elements; ${#arr[@]} gets the length.
More Bash Snippets
Variables and Arrays in Bash
Assign variables, use command substitution, and work with arrays in Bash.
File Operations
File and directory management.
Text Processing
Text processing with grep, sed, awk.
Loops
for and while loops.
Conditionals
if and case conditional statements.
Functions
Function definition and parameters.