Arrays and Tables
Parallel Arrays
Count Matching Rows
Two arrays can model a tiny table when each position belongs to the same row. A loop can scan the rows and count matches.
Program
Play the script to choose a status filter and see how many rows match it.
parallel_array_filter.sh
#!/usr/bin/env bash
ids=("A1" "B2" "C3")
states=("ready" "blocked" "ready")
status_filter=
matches=0
for i in "${!ids[@]}"; do
if [[ "${states[$i]}" == "$status_filter" ]]; then
matches=$((matches + 1))
fi
done
echo "$status_filter:$matches"
#!/usr/bin/env bash
ids=("A1" "B2" "C3")
states=("ready" "blocked" "ready")
status_filter=
matches=0
for i in "${!ids[@]}"; do
if [[ "${states[$i]}" == "$status_filter" ]]; then
matches=$((matches + 1))
fi
done
echo "$status_filter:$matches"
parallel arrays
Parallel arrays use the same index to connect fields from the same row.
array indexes
`${!ids[@]}` expands to the indexes present in the array.
row filter
The loop compares each row's status with the selected filter.