Re: Problem with dynamic statement in bash

From: Tony Mountifield <tony_at_mountifield.org>
Date: Fri, 19 Jan 2018 14:49:37 +0000 (UTC)
Message-ID: <p3t0i1$9lp$1_at_softins.softins.co.uk>


In article <p3sdg6$vti$1_at_news.albasani.net>, Burkhard Schultheis <burkhard.schultheis_at_web.de> wrote:
> Because I must select from several tables depending on the time range I
> must create a dynamic mysql statement in bash. If I execute the
> generated statement in bash, it works. But if I have it in an
> environment variable $statement execute it with $($statement), mysql
> gives the error "mysql: unknown option '--print-defaults'".
>
> The statement looks like this:
>
> mysql <databasename> -N -h <hostname> -e "(select distinct <column1>,
> left(<column2>, locate('[', <column2>)) as versions from <tables1> where
> <condition>) union distinct (select distinct <column1>, left(<column2>,
> locate('[', <column2>)) as versions from <table2> where <condition>)
> order by versions;"
>
> This statement works.
>
> But if I try the following:
> statement="mysql <databasename> -N -h <hostname> -e \"(select distinct
> <column1>, left(<column2>, locate('[', <column2>)) as versions from
> <tables1> where <condition>) union distinct (select distinct <column1>,
> left(<column2>, locate('[', <column2>)) as versions from <table2> where
> <condition>) order by versions;\""
> $($statement)
>
> I get the error "mysql: unknown option '--print-defaults'".
>
> As you can see, I've escaped the two quotation marks.
>
> What's wrong? What to change?

Bash still splits the stored variable when interpolating it, despite the quotes. Do "set -x" before your $($statement) to see.

Why do you put the complete shell command in a variable? Better to store just the SQL query there:

statement="(select distinct <column1>, left(<column2>, locate('[', <column2>)) as versions from <tables1> where <condition>) union distinct (select distinct <column1>, left(<column2>, locate('[', <column2>)) as versions from <table2> where <condition>) order by versions;"

mysql <databasename> -N -h <hostname> -e "$statement"

[Quoted] Even better would be to use an application language such as perl or php.

Cheers
Tony

-- 
Tony Mountifield
Work: tony_at_softins.co.uk - http://www.softins.co.uk
Play: tony_at_mountifield.org - http://tony.mountifield.org
Received on Fri Jan 19 2018 - 15:49:37 CET

Original text of this message