Home > database >  how to create a variable for evaluation in Bash
how to create a variable for evaluation in Bash

Time:03-04

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!

CodePudding user response:

In Bash -- but not necessarily in other shells -- you can reference a variable indirectly, exactly as you seem to want to do:

$ DBServer1=db1.my.com
$ source=DBServer1
$ echo ${source}
DBServer1
$ echo ${!source}
db1.my.com

As the Bash manual puts it:

If [in a parameter expansion of the form ${parameter}] the first character of parameter is an exclamation point (!), and parameter is not a nameref, it introduces a level of variable indirection. Bash uses the value of the variable formed from the rest of parameter as the name of the variable; this variable is then expanded and that value is used in the rest of the substitution, rather than the value of parameter itself.

Applying that to your sample code and data, we get

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

# ...

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

CodePudding user response:

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"
  • Related