user385411
user385411

Reputation: 81

how can use bash and mysql with while and output

how can I write the different queries into the same file.

#!/bin/bash
while IFS= read -r line
do
mysql -udata -pdata database <<EOF
SELECT ID,name,grp,Status,ctime FROM database WHERE name LIKE '$line' INTO OUTFILE '/tmp/out.txt'
EOF
done < /tmp/input.txt



Error:
ERROR 1086 (HY000) at line 1: File '/tmp/out.txt' already exists

.

and with ">>" instead of "INTO OUTFILE" is error:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '>> '/tmp/out.txt'' at line 1

Upvotes: 0

Views: 140

Answers (1)

chepner
chepner

Reputation: 531315

Put the redirection on the command line, not in the here document.

while IFS= read -r line
do
mysql -udata -pdata database <<EOF >> /tmp/out.txt
SELECT ID,name,grp,Status,ctime FROM database WHERE name LIKE '$line'
EOF
done < /tmp/input.txt

or

while IFS= read -r line
do
mysql -udata -pdata database <<EOF
SELECT ID,name,grp,Status,ctime FROM database WHERE name LIKE '$line'
EOF
done < /tmp/input.txt > /tmp/out.txt

Before running this code, though, be sure to read about SQL injection; it is generally a bad idea to construct dynamic SQL queries using string interpolation.

Upvotes: 1

Related Questions