Multiple times in a day I type the same commands and therefore thought it might be good to write a shell script to save me the repetition. I also thought this might be a good way to learn a little more about shell coding, as I normally work with OOP languages.
The code should open an ssh connection to my server, then start mysql and select the database I wish to use. I'm struggling to make the code work. I guessing it's because the bash script is on my local machine and I need somehow to execute if on the remote machine. I can't find any examples of how to do this. Here's my code:
#!bin/bash
#Script to automate login to remote server and select specific mysql database
password="myPassword"
username="myUserName"
remoteuser="myUsername@my.se.rv.er.00"
echo "Attempting login to server.."
#attempt ssh connection to remote server...
status=$(ssh -o BatchMode=yes $remoteuser echo ok 2>&1)
#if connection is made...
if [[ $status == ok ]] ; then
echo "connection established"
echo "attempting mysql login..."
#attempt to start mysql and select my database
mysql --user=$username -p$password -Bse"USE mydatabase; show tables;"
elif [[ $status == "Permission denied"* ]] ; then
echo "Permission denied"
else
echo "other_error"
fi
when I run this I get the error: ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock'
How do I fix this code? I am interpreting this error message correctly: the reason my script isn't working is because the mysql command is being ran on my machine rather than the server?
The aim of the code is not to boot a script running on my server, it's to make a complete script that connects to my server, confirms the connection and then logs me into mysql on the remote machine so that I can then continue working on it through my own terminal.