Languages
[Edit]
EN

Bash - create 2D array

7 points
Created by:
Mark-Rotteveel
477

In this short article, we would like to show how to create 2D array in Bash.

By default Bash doesn't support 2D arrays, but there is some trick that lets to achieve the effect.

Quick solution (address array with ${array[row_index * columns_count + column_index]}):

#!/bin/bash

columns_count=2

array=(
#  [column 0]  [column 1]
	a           b
	c           d
	e           f
)

items_count=${#array[*]}
rows_count=$((items_count / columns_count))

echo "Array size: $rows_count x $columns_count"

row_index=2
column_index=1

echo "Array item: ${array[row_index * columns_count + column_index]}"

Output:

Array size: 3 x 2
Array item: f

Note: in the array, white characters between items are ignored, so to add item with multiple words wrap it with "".

e.g.

array=(
#  [column 1]  [column 2]
	"a item"   "b item"
	"c item"   "d item"
	"e item"   "f item"
)

 

Practical example

In the below example we use a users list that contains rows with two columns: username and email.

#!/bin/bash

columns_count=2

users=(
#  [column 0]  [column 1      ]
#
	john        john@mail.com
	ann         ann@mail.com
	matt        matt@mail.com
)

items_count=${#users[*]}
rows_count=$((items_count/ columns_count))

echo "Users count: $rows_count"
echo

for (( i = 0; i < rows_count; ++i ))
do
	row_number=$((i + 1))

	echo "$row_number. ${users[i * columns_count + 0]} ${users[i * columns_count + 1]}"
done

Output:

Users count: 3

1. john john@mail.com
2. ann ann@mail.com
3. matt matt@mail.com

 

Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join