Sunday, May 5, 2024
 Popular · Latest · Hot · Upcoming
24
rated 0 times [  24] [ 0]  / answers: 1 / hits: 39820  / 3 Years ago, mon, october 18, 2021, 12:51:09

There are a lot of guides out there which show how to declare and define an array



foo[0]=abc 
foo[1]=def


What I am trying to achieve is to declare an array but not define it because it does not have to be define immediately , in most programming languages it will look something like this



int bar[100];


Is this possible in shell scripting language?


More From » bash

 Answers
1

You can specify that a variable is an array by creating an empty array, like so:



var_name=()


var_name will then be an array as reported by



$ declare -p var_name
declare -a var_name='()'


Example:



var_name=()
for i in {1..10}; do
var_name[$i]="Field $i of the list"
done
declare -p var_name
echo "Field 5 is: ${var_name[5]}"


which outputs something like this:



declare -a var_name='([1]="Field 1 of the list" [2]="Field 2 of the list" [3]="Field 3 of the list" [4]="Field 4 of the list" [5]="Field 5 of the list" [6]="Field 6 of the list" [7]="Field 7 of the list" [8]="Field 8 of the list" [9]="Field 9 of the list" [10]="Field 10 of the list")'
Field 5 is: Field 5 of the list

[#27583] Tuesday, October 19, 2021, 3 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
ongdiligenc

Total Points: 452
Total Questions: 111
Total Answers: 107

Location: Ukraine
Member since Sun, Dec 13, 2020
3 Years ago
;