Sample Header Ad - 728x90

Concatenating string to form an existing variable name and working within array enclosure format

0 votes
2 answers
674 views
#!/bin/bash
mat_1=(ServerAB ServerFR ServerPE ServerAM ServerHU)
st="mat_1";
indirect_var='${'${st}'[@]}'

#(Please, see the "--Desired Ouput Section--" in comments)

#----- What is Hapenning now at output ----
echo Values of "mat_1 ": ${mat_1[@]}
echo Indirect value of "mat_1": ${!indirect_var}

# echo Indirect value of "mat_1": ${!indirect_var}  ##output> ${mat_1[@]}
# But it is not recognized as a real ${mat_1[@]}.

# -- What actually have ----
for (( i=0; i  function-name $1, where $1 is
                                     # an string, and this string already
                                     # exist above , it will interpret as
                                     # an existing array
 

do
   echo ${mat_1[i]};
done

#And I would like those strings 
#that are part of the name of existing 
#variables , will be treated as an input
# and this loop works. I will show What I have done,
# what I have reached, and what I expect to have.
# Thank you!


#------What I expect works-----

#for (( i=0; i < ${#$st[@]}; i++ ))  #I would like $st works like 'mat_1'
                                     #and this loop can be run without 
                                     #problems
#do
#   echo ${$st[i]};
#done

#--- Actual Output ------------
#$ ./matrix.sh 
# Values of mat_1 : ServerAB ServerFR ServerPE ServerAM ServerHU
# ./matrix.sh: line 8: ${mat_1[@]}: invalid variable name
# ServerAB
# ServerFR
# ServerPE

#--- Desired Output ----------

#$ ./matrix.sh 
# Values of mat_1 : ServerAB ServerFR ServerPE ServerAM ServerHU
# Indirect Value of mat_1: ServerAB ServerFR ServerPE ServerAM ServerHU
# ServerAB
# ServerFR
# ServerPE
# ServerAM
# ServerHU
" Hi Friends, I would like some ideas to achieve the following". - I have many existing 'arrays vars' that I would like to be called within a for loop by 'concatenating strings' in order to form those ' existing array names'.But in the Script above I just only Working with 01 array 'var_mat1'. I jut only need work for 01 array... - Example of the existing 'array names': var_mat1=( ".." ".." ".." ) var_mat2=( ".." ".." ".." ) . . . var_matN=( ".." ".." ".." )
Asked by dcubaz (23 rep)
Apr 12, 2021, 04:23 PM
Last activity: Apr 12, 2021, 09:13 PM