just wondering if it's possible to generate a 2D array if the dimension is not known prior to user input. For example if user input 2 2 on the commandline the shell will generate a 2D array base on that? thank you
just wondering if it's possible to generate a 2D array if the dimension is not known prior to user input. For example if user input 2 2 on the commandline the shell will generate a 2D array base on that? thank you
bash
is an interpreted language, and it doesn't need to know how much memory to allocate in advance.
So it's possible to dinamically initialize a new array without having declared it or to expand an already declared array to add more entries, however it's not possible to use multidimensional arrays.
However this can be faked: since you didn't provide an exact task to accomplish, I'll provide a bash
script example which shows how to fill in an user-defined m x n
table with random numbers (which are not really random, since each column will always have the same number on all its rows in each run, but this is not relevant to the question) and print it (simplified from this Stack Overflow answer):
#!/bin/bash
declare -a array
read -p 'm: ' m
read -p 'n: ' n
for ((i=0; i<m; i++))
do
for ((j=0; j<n; j++))
do
a[${i},${j}]=$RANDOM
done
done
for ((i=0; i<m; i++))
do
for ((j=0; j<n; j++))
do
echo -ne "${a[${i},${j}]} "
done
echo
done