0

I want to write a shell script where I want to connect to a MySQL database server by providing user id and password in the shell script only and then run my drop and create database queries. The server will be in a different box-like Rubik. Any help would be highly appreciated.

2
  • Kindly post some of your code / efforts, then only we can help you. Commented Nov 20, 2019 at 6:36
  • I am using a gcloud to connect. I am writing first time shell scripts so forgive if i sound wrong. I log in to my cluster and the run my glcoud command -> gcloud sql connect ql03-dd97-mysql --user=root --quiet . So now, I want to write the script to directly access it from my .sh file and by providing id and password and it should connect it. Commented Nov 20, 2019 at 7:04

1 Answer 1

4

first you need a mysql client, install it if you don't have it

apt-get install mysql-client

then you must write like this:

#!/bin/bash
USER='username'
PASS='password'
PORT=3160
HOST='hostname'
DBASE='mysqlDbName'

Query='SELECT * FROM table WHERE some=other LIMIT 10'

mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF 
$Query
EOF

// or you simple write the MYSQL code like
mysql -u$USER -p$PASS -P$PORT -h$HOST -D$DBASE <<EOF
USE mysql
SHOW tables
SELECT * FROM table WHERE some=other LIMIT 10
DROP table
EOF

// or in shell script and save your result to a file
#!/bin/bash
mysql -u$USER -p$PASS -h$HOST -A \
 --default-character-set=utf8 \
 -e $Query > /home/user/result.txt
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.