Home > OS >  Iterate through sql result in shell script
Iterate through sql result in shell script

Time:12-31

I am using the below code

tablelist=`SELECT tablename from List`
echo "table list is $tablelist"

Result is displayed as

table list is Table1
Table2
Table3
Table4

I want to iterate through the result. Please suggest how I can achieve this. If I loop through the current tablelist, it prints the whole list in inside loop.

CodePudding user response:

"${tablelist}" is not a one-line result. It is multiple lines, one entry per line. So ... it is best not to treat it as a simple string. You should treat it as a file.

#!/bin/bash

#tablelist=`SELECT tablename from List`

cat >tables.list <<"EnDoFiNpUt"
Table1
Table2
Table3
Table4
EnDoFiNpUt

i=1

#echo "${tablelist}" |
cat tables.list |
while read table
do
        echo -e "\t [${i}] TABLE: '${table}' ..."
        echo -e "\t\t ... replace this line by some action using '${table}' ...\n"
        i=$((i =1))
done

The output of that looks like this:

[1] TABLE: 'Table1' ... ... replace this line by some action using 'Table1' ...

[2] TABLE: 'Table2' ... ... replace this line by some action using 'Table2' ...

[3] TABLE: 'Table3' ... ... replace this line by some action using 'Table3' ...

[4] TABLE: 'Table4' ... ... replace this line by some action using 'Table4' ...

  • Related