Wednesday, April 13, 2022

[SOLVED] how to create a variable for evaluation in Bash

Issue

I have a CSV that says this:

Source,Target,Database,Table,Is_deletable,Action
DBServer1,DBServer2,DB,TBL1,true,Add
DBServer2,DBServer1,DB,TBL2,true,Add

I have shell script that does this:

while IFS=, read -r source target database table is_deletable action; do
    echo "Building pipeline for ${database}.${table}";
              total=$((total+1))
              Shost="server1.myorganization.com"
              Thost="server2.myorganization.com"

I need Shost to look like this:

Shost = ${'the value of the source column'}
Thost = ${'the value of the target column'}

How do I set this to evaluate dynamically the variable I need based on the value of the column data.

For example:

Shost=${DBServer1}
Thost=${DBServer2}

then on the next loop:

Shost=${DBServer2}
Thost=${DBServer1}

Thanks!


Solution

Something like this should work for you:

DBServer1='server1.myorganization.com'
DBServer2='server2.myorganization.com'

while IFS=, read -r source target database table is_deletable action; do
   [[ $source = "Source" ]] && continue
   ((total++))
   Shost="${!source}"
   Thost="${!target}"

   # check variables Shost Thost total
   declare -p Shost Thost total
done < file.csv

declare -- Shost="server1.myorganization.com"
declare -- Thost="server2.myorganization.com"
declare -- total="1"
declare -- Shost="server2.myorganization.com"
declare -- Thost="server1.myorganization.com"
declare -- total="2"


Answered By - anubhava
Answer Checked By - Mildred Charles (WPSolving Admin)