3

I want to create a database on a remote server through ssh with a bash script. Something like this

#!/bin/sh
ssh [email protected] 'mysql -h example.com -uroot -pMYPASSWD -e "CREATE DATABASE $1;"'

So that I in terminal can run it like

$ myBashScript nameOfNewDatabase
5
  • Try this: ssh [email protected] "mysqladmin create $1" Commented Oct 15, 2012 at 22:50
  • manpagez.com/man/1/mysqladmin gives details of options, e.g. --user=root --password=MYPASSWD etc. Commented Oct 15, 2012 at 22:52
  • Got error bash: mysqladmin: command not found, got the same when I tried the one I wrote in desc, but mysql is installed. I'll check if mysqladmin is installed. Commented Oct 15, 2012 at 22:54
  • Mysqladmin is installed, but when I try to run the command remotely with ssh [email protected] "mysqladmin create $1" it gives me the error above. Commented Oct 15, 2012 at 22:57
  • Be aware that "mysqladmin" is not the local one, it's the one installed on the server. Try something like ssh [email protected] "/path/to/mysqladmin create $1" and forget about relying on your remote PATH settings .. Commented Jan 30, 2013 at 14:41

1 Answer 1

3

The following script can remotely execute arbitrary commands

#!/bin/bash
# call mysql on a remote server to execute the given command 

# show usage and exit
usage() {
  echo "$0 server sql-command"  1>&2
    exit 1
}

# check number of arguments
if [ $# -lt 2 ]
then
  usage
fi

# get server name and sql command
server="$1"
sql="$2"

# copy command to a temporary file
tmpsql="/tmp/sql$$"
echo "$sql" > $tmpsql

# copy command file to server
scp $tmpsql $server:$tmpsql
# run command remotely with removing command file afterwards
ssh $server "mysql -uroot -pPASSWORD < $tmpsql;rm $tmpsql"
# remove local copy of command file
rm $tmpsql
Sign up to request clarification or add additional context in comments.

8 Comments

Awesome! So, it scp's a script file to the server, then executes it? I'll check it out later today.
It throws me: bash: mysql: command not found Is there some setting I'm missing on the server?
you need to make sure the PATH is set in the ssh session or specify the fully qualifying name of mysql in the script. Use "which mysql" in a ssh terminal session to find it e.g. >which mysql /usr/local/mysql/bin/mysql
So it does not help that the PATH is set in the bash profile on the server, I have to somehow declare it in this script as well? How would that be done?
with macports I have to put the PATH declaration in .ssh/environment e.g. PATH=/usr/bin:/bin:/usr/sbin:/sbin:/opt/local/bin
|

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.