简体   繁体   中英

How to make a Bash insert script for MySQL

I've been trying for two days to make a simple script which feeds an argument (a query) to mysql -e for it to execute. But I can't use mysql -e inside the script for some reason, here are my testings :

I can run the following line in my bash with success :

mysql -u abrouze -p simubase -e "insert into Processing values(1,2,3,'coca cola')"

It might be important to note that I need to pass full strings with whitespaces in the values.

Now, here is my script :

#!/bin/bash
req="\"$1\""
echo $req
mysql -u abrouze -p simubase -e $req

Escaping quotes here so $req is really surrounded by quotes, and it doesn't work.

Trace :

brouze@lasb-ida:~$ ./myrage.sh "insert into Processing values(1,2,3,'huge bear')"
"insert into Processing values(1,2,3,'huge bear')"

mysql  Ver 14.14 Distrib 5.5.35, for debian-linux-gnu (x86_64) using readline 6.2
Copyright (c) 2000, 2013, Oracle and/or its affiliates. All rights reserved.

Following this, the help wall-of-text.

It seems absolutely trivial to me, I absolutely don't know how it would not work...

You can use a heredoc for this, have your script be:

#!/bin/bash
mysql -u abrouze -p simubase << EOF
$1
EOF

Then call your script as before:

./myrage.sh "insert into Processing values(1,2,3,'huge bear');"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM