2

My bash script queries a mysql database 3 times and redirects the standard out of each query to a file (3 different files in total with different columns structure ).

I want it to ask for the mysql password as it's important for me not to have the password in the script or on disk.

How can I include all queries and stdout redirection in the same mysql session in order to avoid asking for the password 3 times?

This is what I have now:

#!/bin/bash 
mysql -h database.com -u user -p -e "USE database; mysql query1"  > file1
mysql -h database.com -u user -p -e "USE database; mysql query2"  > file2
mysql -h database.com -u user -p -e "USE database; mysql query3"  > file3
codeforester
  • 39,467
  • 16
  • 112
  • 140
TheRose
  • 51
  • 2

2 Answers2

0

You could use tee and notee commands and write a single query file, say queries.sql and invoke it in a single shot:

use database
tee file1
query1
notee
tee file2
query2
notee
tee file3
query3
notee

Then invoke it:

mysql -h database.com -u user -p -e "source queries.sql" > /dev/null

Related:

codeforester
  • 39,467
  • 16
  • 112
  • 140
0

You could use bash to prompt for the password, and then supply it to each of the mysql commands:

#!/bin/bash

echo "enter the password for MySQL:"
read -s PASSWD

mysql -h database.com -u user -p$PASSWD -e "USE database; mysql query1"  > file1
mysql -h database.com -u user -p$PASSWD -e "USE database; mysql query2"  > file2
mysql -h database.com -u user -p$PASSWD -e "USE database; mysql query3"  > file3

Here is a POSIX-compliant version of silent prompting for non-bash shells:

stty -echo
printf "enter the password for MySQL:"
read PASSWD
stty echo
printf "\n"
landru27
  • 1,654
  • 12
  • 20