Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Execute multiline mysql in shellscript

Tags:

bash

mysql

When I attempt to execute a multi-line SQL in mysql via shell script:

mysql -uroot -ppass mydb <<<EOF
SELECT * INTO OUTFILE 'table.csv'
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
    LINES TERMINATED BY '\n'
FROM mytable limit 1;
EOF

I get a syntax error:

ERROR 1064 (42000) at line 1: You have an error in your SQL syntax; check the manual that
corresponds to your MySQL server version for the right syntax to use near 'EOF' at line 1

What's the right way to script it?

like image 879
user121196 Avatar asked Jan 10 '12 10:01

user121196


People also ask

How run multiple SQL queries in shell script?

sh script to execute multiple MySQL commands. mysql -h$host -u$user -p$password -e "drop database $dbname;" mysql -h$host -u$user -p$password -e "create database $dbname;" mysql -h$host -u$user -p$password -e "another MySQL command" ...

How do I run multiple queries in MySQL?

Multiple statements or multi queries must be executed with mysqli::multi_query(). The individual statements of the statement string are separated by semicolon. Then, all result sets returned by the executed statements must be fetched.

How do I run a SQL script in MySQL shell?

Learn MySQL from scratch for Data Science and Analytics To run SQL script in MySQL, use the MySQL workbench. First, you need to open MySQL workbench. Now, File -> Open SQL Script to open the SQL script. Note − Press OK button twice to connect with MySQL.

How do I run a SQL query in a bash script?

Run queries with “-e” option Basically, if you merely want to run a simple and short SQL query, use the -e option following the query. As the above code shows, the -D option is to specify which database to use and the -e option can execute a query.


1 Answers

The syntax for bash heredoc is:

COMMAND <<InputComesFromHERE
...
...
...
InputComesFromHERE

So you have an extra <.

In order to prepare and test you can replace COMMAND (i.e. mysql -uroot -ppass mydb in this case) with cat to have a look at the exact SQL code that will be executed.

like image 163
Álvaro González Avatar answered Oct 01 '22 09:10

Álvaro González