Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

I'd like to run multiple MySQL queries and save them to specified files. Queries are saved in a bash script, queries.sh, e.g.:

cat queries.sh
mysql -u <user> -p <DBname> -e "select Col1 from Table1 where Condition;" > /home/<user>/queries/Col1Table1Cond
mysql -u <user> -p <DBname> -e "select Col5 from Table2 where Condition;" > /home/<user>/queries/Col5Table2Cond

Executing the script is not enough, since <user> has to input his password at each query and this is compromising the script flow.

share|improve this question
    
So what do you plan to do ? Keep the password in a variable ? Parse commandline switch ?? – Gilles Quenot Sep 25 '16 at 12:36
    
How about storing the password as an environment variable or in another file? – Barun Sep 25 '16 at 12:37
up vote 2 down vote accepted

Try this ;)

user="jonnDoe"
dbname="customers"
password="VerySecret"

mysql -u $user -D $dbname -p $password -e "select Col1 from Table1 where Condition;" > /home/$user/queries/Col1Table1Cond
mysql -u $user -D $dbname -p $password -e "select Col5 from Table2 where Condition;" > /home/$user/queries/Col5Table2Cond

A better practice is to configure mysql /etc/mysql/my.cnf file with the password inside, this way, no need to enter it each times :

[client]
password    = your_password

In this later case, remove all password related things from previous script

share|improve this answer

There usually are a few different ways to achieve this.

Store it in an external file containing only the password:

$cat password.txt
Password

$cat queries.sh
mysql -u <user> -p$(cat password.txt) <rest of the command>

Store it in another shell script:

$cat settings.sh
PASSWORD=Password

$cat queries.sh
source settings.sh
mysql -u <user> -p"$PASSWORD" <rest of the command>

Store it in an environment variable called PASSWORD:

$cat queries.sh
mysql -u <user> -p"$PASSWORD" <rest of the command>

Also, see How to auto login mysql in shell scripts?

share|improve this answer
1  
Thanks Barun. I think this solution is more portable if the script needs to be executed by different users with personal password. – dovah Sep 25 '16 at 12:51

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.