Loop running only for first line shell script

Asked

Viewed 46 times

0

I need to make a script that reads a list of querys of a txt file, and save the result of each query in a file with the table name.

My script went like this:

#!/bin/bash
oIFS="$IFS"
IFS=;

QUERYS="`cat /tmp/querys.txt`"

for query in $QUERYS
do
    TABELA=`echo $QUERYS|awk -F"from" '{print $2}'|cut -d' ' -f2`
    `mysql -uroot -h127.0.0.1 -P3307 damasio_dados -e "$query" > /tmp/$TABELA`
    done

IFS="$oIFS"

If my "/tmp/querys.txt" file has the following content:

select * from wmsstk ;

Works correctly and generates the file "/tmp/wmsstk" correctly with the result of select.

But if the file has the following content:

select * from wmsstk ;
select * from wmsadd ;

Generating the file "/tmp/wmsadd? wmsstk" with the contents of the two selects.

Obs.: I know there may be a simpler way to do it, but it was the way I managed to get some head start.

1 answer

0


Worked with small changes, basically in IFS and using var $query in TABLE

#!/bin/bash
IFS='
'
QUERYS=$(cat /tmp/querys.txt)

for query in $QUERYS
do
    TABELA=$(echo $query|awk '{print $4}')
    $(mysql -pSENHA -uroot -h 127.0.0.1 -P3307 damasio_dados -e "$query" > /tmp/$TABELA)

done

PS: in my example I needed to pass the Mysql password. If you don’t need it, remove -pSENHA.

  • I confused the variables $query and $QUERYS in the same loop... The big deal was the $IFS that I didn’t know how to use.. Now the command (gambiarra) to get the table name, I did it that way because not always my string will be "select * from", It may sometimes have only the columns I need. This I do not know if it is the best way to do. Anyway it worked.

  • Got it! then you can use your mode to get the table name. !

Browser other questions tagged

You are not signed in. Login or sign up in order to post.