Contents
Can you create a two dimensional array in Bash?
Bash does not support multi-dimensional arrays, but there is a way to imitate this functionality, if you absolutely have to. As a quick example, here’s a data table representing a two-dimensional array. And here’s the graphical representation of this two-dimensional array with the values you would expect for each y [x] position:
What’s the problem with a for loop in Bash?
The problem is that the for loop will resolve your arrays into their elements and treat each element separately. Therefore, deconstruct your arrays and make them again. Thanks for contributing an answer to Unix & Linux Stack Exchange!
How to iterate over two arrays simultaneously in Bash?
From anishsane’s answer and the comments therein we now know what you want. Here’s the same thing in a bashier style, using a for loop. See the Looping Constructs section in the reference manual. I’m also using printf instead of echo. Another possibility would be to use an associative array:
How are multi-dimensional arrays used in Stack Overflow?
This works thanks to 1. “indirect expansion” with ! which adds one layer of indirection, and 2. “substring expansion” which behaves differently with arrays and can be used to “slice” them as described https://stackoverflow.com/a/1336245/317623
Is there a Unix shell that supports arrays?
Those are two different answers. The POSIX specification for shells does not have anything to say about arrays, as the original Bourne shell did not support them. Even today, on FreeBSD, Ubuntu Linux, and many other systems, /bin/sh does not have array support.
Do you need arrays in a bash script?
But what if you need more than few variables in your bash scripts; let’s say you want to create a bash script that reads a hundred different input from a user, are you going to create 100 variables? Luckily, you don’t need to because arrays offer a much better solution.
How to declare 2D array in Bash-Stack Overflow?
If each row of the matrix is the same size, then you can simply use a linear array and multiplication. This approach might be worth turning into a set of functions, but since you can’t pass arrays to or return arrays from functions, you would have to use pass-by-name and sometimes eval.
How to iterate through an array in Bash?
If you want to use a bash script and keep it easy to read recommend putting the data in structured JSON, and then use lightweight tool jq in your bash command to iterate through the array. For example with the following dataset: You can iterate through this data with a bash script and jq like this: