Assign output to dynamic variable

Hi Folks,

I am trying to assign a value from the command to a dynamic variable. But I am not getting the desired output.. I am sure something is wrong so i need experts advise.

There will be multiple files like /var/tmp/server_1, /var/tmp/server_2, /var/tmp/server_3, having different server names in each file

cat /var/tmp/server_1
ssp01
ssp02
ssp03
ssp04

cat /var/tmp/server_2
ssp05
ssp06
ssp07

cat /var/tmp/server_3
ssp08
ssp09

The script below does read the file one by one, but i am finding the hard part in assigning the grep output to the dynamic variable SERVERS_${i}.

                FILE_NAME="/var/tmp/server"
                COUNT=`ls -ltr $FILE_NAME*| wc -l|awk '{print $1}'`
                for (( i=1; i<=${COUNT}; i++ ))
                do
                        SERVERS_FILE="${FILE_NAME}_${i}"
                        SERVERS_${i}="`grep ssp $SERVERS_FILE`"
                        echo Server names in SERVERS_${i}: "${SERVERS}_${i}"
                done

                 

Eventually, i wanted to see the output

Server names in SERVERS_1: ssp01 ssp02 ssp03 ssp04
Server names in SERVERS_2: ssp05 ssp06 ssp07
Server names in SERVERS_3: ssp08 ssp09

Thanks in advance for your help !!

You could use something as simple as this:

for i in server_*
do
 echo Server names in $i: $(<$i)
done

try with this..

SERVERS_${i}="`grep ssp $SERVERS_FILE | tr '\n' ' '`"

Thanks Elixir.. But i want it to be assigned to the dynamic variable SERVERS_${i} as i have to perform some other manipulation with the end result..

Then, you may use an indexed array:

for i in server_*
do
 num=${i##*_}
 SERVERS[$num]=$(tr '\n' ' ' <$i)
 echo "${SERVERS[$num]}"
done

If you want to assing values to variables (better: to elements of an array), you can do like that (in GNUlinux/bash):

$ FILES=( $(find /var/tmp -maxdepth 1 -type f -name "server_[0-9]*" -printf %f" ") )
$ declare -A NAMES    ###this opens an associative array
$ for SERVER in "${FILES[@]}"; do NAMES[$SERVER]=$(grep ssp "$SERVER"); done

If you want to print to screen the servers names, then:

$ for SERVER in "${FILES[@]}"; do echo -e "${SERVER} names are:\n${NAMES[$SERVER]}"; done

--
Bye

Thanks Pamu.. I got the below output adding tr so i added export in front of it

./test: line 6: SERVERS_1=ssp01 ssp02 ssp03 ssp04 : command not found
_1
./test: line 6: SERVERS_2=ssp05 ssp06 ssp07 : command not found
_2
./test: line 6: SERVERS_3=ssp08 ssp09 : command not found
_3

export SERVERS_${i}="`grep ssp $SERVERS_FILE | tr '\n' ' '`"

However, i am getting the following result doing echo "${SERVERS}_${i}"

ssp01
ssp02
ssp03
ssp04_1
ssp05
ssp06
ssp07_2
ssp08
ssp09_3