Chris
Chris

Reputation: 107

mysql bash shell script outputting erro

I am trying to create a bash shell script that runs an sql query and later on create a cronjob that runs it at an specific time.

I created my bash script see below

mysql -u $host -D $dbname -u $user -p$password -e $mySqlQuery

I have wrap -u -D -p -e all in variables. I have also change it to and executable file. When i run it. it gives out an output stating. Command not found. can anyone tell the mistake i made?

Below is the bash script

host="host"
user="user"
dbname="database"
password="password"
mySqlQuery = "SELECT *
FROM invoice i
  JOIN item it
    ON it.invoice_id = i.id
  JOIN user u
    ON i.user_id = u.id
  JOIN gateway_response gr
    ON gr.invoice_id = i.id

WHERE  i.created_at >= '2019-03-01 00:00:00' and
i.created_at <= '2019-03-17 23:59:59' and i.status=9"

mysql -u $host -D $dbname -u $user -p$password -e $mySqlQuery

Below is the error i am receiving when i run it.

/home/chris2kus/givingDetectRun.sh: line 8: mySqlQuery: command not found /home/chris2kus/givingDetectRun.sh: line 20: mysql: command not found – 

Upvotes: 0

Views: 48

Answers (3)

Rod Elias
Rod Elias

Reputation: 746

There must be no spaces around the = and the variable name mySqlQuery.

Also, I suggest you wrap your variables around double quotes, i.e., use "$host" instead of just $host.

Upvotes: 1

Nikola Pavlovic
Nikola Pavlovic

Reputation: 101

For starters, make sure your line 5 looks like mySqlQuery="SELECT..."

(notice no spaces on either side of the assignment operator)

For seconds, try to re-format your entire MySQL query to fit into a single line. (perhaps Heidi since it's a query, since that will keep you at least syntax-wise in the clear of errors)

For thirds, once you confirm that the bash runs as intended, add \n to tell the bash that you're continuing the command in the next row

Prototyping before optimization. Get it running before you get it flying.

Upvotes: 0

Bernd Buffen
Bernd Buffen

Reputation: 15057

You can write a file like this and chmod 755 filename.sh :

#!/bin/bash

host="localhost"
dbname="test"
user="root"
password="xxxxxxxxxx"

mySqlQuery="select * 
from col;"

mysql -u $host -D $dbname -u $user -p$password -e "$mySqlQuery"

Sample

$chmod 755 testmysql.sh
$
$ ./testmysql.sh 
+----+------+------+------+
| id | Col1 | Col2 | Col3 |
+----+------+------+------+
|  1 |    1 |    2 |    3 |
|  2 |    2 |    3 |    4 |
|  3 |    3 |    4 |    5 |
+----+------+------+------+
$

Upvotes: 0

Related Questions