Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

bash and mysql

16 views
Skip to first unread message

James

unread,
Apr 3, 2015, 7:55:18 PM4/3/15
to
To feed query into mysql, below syntax fails if query contains some characters such as (*,',",$,etc.). How do I escape $query?

printf "$query" | mysql -h <host> -u <user> -A <db> -p <pw>


TIA
James

Ben Bacarisse

unread,
Apr 3, 2015, 9:33:01 PM4/3/15
to
James <hsle...@yahoo.com> writes:

> To feed query into mysql, below syntax fails if query contains some
> characters such as (*,',",$,etc.).

Saying how something fails is usually the first step. Everyone reading
this is working with less information than you have!

> How do I escape $query?
>
> printf "$query" | mysql -h <host> -u <user> -A <db> -p <pw>

The only problem character would be % (which printf interprets as a
format) or a leading -- sequence which might look like an option. You
can fix both by using

printf "%s" "$query" | ...

I think you may be asking something slightly different, but a fuller
example of what you tried and what goes wrong would be needed to be
sure.

--
Ben.

Barry Margolin

unread,
Apr 3, 2015, 9:39:47 PM4/3/15
to
In article <648ad4ea-4770-48b6...@googlegroups.com>,
Why are you using printf if you're not doing formatting? Just use echo:

echo "$query" | mysql ...

--
Barry Margolin, bar...@alum.mit.edu
Arlington, MA
*** PLEASE post questions in newsgroups, not directly to me ***

Martijn Dekker

unread,
Apr 6, 2015, 9:25:52 PM4/6/15
to
The first argument to printf cannot be an arbitary string. It's the
formatting spec for the string to print. You want:

printf '%s\n' "$query" | etc.

Note: "echo" is not portable between different shells, so if you use it,
be sure your scripts starts with #!/bin/bash instead of #!/bin/sh

Geoff Clare

unread,
Apr 8, 2015, 8:41:09 AM4/8/15
to
Barry Margolin wrote:

> In article <648ad4ea-4770-48b6...@googlegroups.com>,
> James <hsle...@yahoo.com> wrote:
>
>> To feed query into mysql, below syntax fails if query contains some
>> characters such as (*,',",$,etc.). How do I escape $query?
>>
>> printf "$query" | mysql -h <host> -u <user> -A <db> -p <pw>
>
> Why are you using printf if you're not doing formatting? Just use echo:
>
> echo "$query" | mysql ...

Different versions of echo behave differently if arguments contain
backslashes, or if the first argument is -n, -e or -E. So echo
should only be used to output fixed strings which are known not
to contain backslashes and are not -n, -e or -E.

James was right to use printf to print his "$query" string; he just
left out the format-string argument that should have preceded it:

printf '%s\n' "$query" | mysql ...

--
Geoff Clare <net...@gclare.org.uk>

Luuk

unread,
Apr 11, 2015, 5:34:29 AM4/11/15
to
why not use:
mysql -h <host> -u <user> -A <db> -p <pw> -Be "$query"
0 new messages