Friday, May 3, 2024
2
rated 0 times [  2] [ 0]  / answers: 1 / hits: 11505  / 3 Years ago, tue, september 7, 2021, 3:20:18

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


More From » command-line

 Answers
4

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

[#19626] Wednesday, September 8, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
irtuallyefu

Total Points: 429
Total Questions: 97
Total Answers: 119

Location: Hong Kong
Member since Tue, Oct 19, 2021
3 Years ago
irtuallyefu questions
;