combining 3 separate arrays to one multidimensional array in bash
From man 1 bash
:
Arrays
Bash provides one-dimensional indexed and associative array variables. Any variable
may be used as an indexed array; the declare builtin will explicitly declare an
array. There is no maximum limit on the size of an array, nor any requirement that
members be indexed or assigned contiguously. Indexed arrays are referenced using
integers (including arithmetic expressions) and are zero-based; associative arrays
are referenced using arbitrary strings. Unless otherwise noted, indexed array
indices must be non-negative integers.
Key phrase:
Bash provides one-dimensional indexed and associative array variables.
So, no, bash does not support multi-dimensional arrays.
I ran into this just now. There is a fairly simple solution that worked for me. I wanted to use an array that contained a device name and a screen position to display a key map for the device. I did the following:
I concatenated the device name and the associated screen position
into a single string, using a delimiter (in my case, I used .
)
that I knew would not appear in any of my values.
Then I used cut
to break the composite values apart into their components
when needed. There might be a cleaner and simpler way to do this, but this is just to show that you can create a multidimensional array, in a way, in bash, even though it doesn't support it:
#!/bin/bash
# List of devices and screen positions for key maps.
DEV_LIST=( g13.+2560+30 g510s.+3160+30 g502.+2560+555 )
# This just echoes the device name and the screen position.
for DEV in "${DEV_LIST[@]}"; do
DEVICE=$(echo $DEV | cut -f1 -d.)
SCREEN_POSITION=$(echo $DEV | cut -f2 -d.)
echo "$DEVICE"
echo "$SCREEN_POSITION"
done
exit
This is somewhat similar to Coop.Computer’s answer.