1

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...

2
  • 1
    echo ${req} | mysql... maybe? Your quotes are all wrong. There should not be quotes in the string, they should be around the string. So req=$1 and then use "${req}". Commented Apr 10, 2014 at 10:45
  • As you said req=$1,echo ${req} | mysql... works. More simply, echo $1 | mysql... works too. As for why quotes inside the string is not the same as outside the string, I suppose it's because of Bash's behavior on parsing strings based on the quoting used. Commented Apr 10, 2014 at 14:52

1 Answer 1

1

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');"
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, it works. I would like to understand the mechanic though. Since I had provided the exact same string "insert into..." to mysql, why did that not work ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.