Mysql – Special characters in thesql password using thesqldump

centos6MySQLmysql5.5

I have the following ssh script:

#Here I am getting the mysql password for the root user
password=$(cat /root/.my.cnf | grep "password" |  awk -F\" '{print $2}') 

#here I am trying to dump the database remotely
mysqldump -uroot -p$password $db |  ssh root@$destination_server "cat > /backup/mysql/$db.sql"

The thing is that I am getting the following error:

/bin/bash: -c: line 0: syntax error near unexpected token `)'
/bin/bash: -c: line 0: `mysqldump -uroot -pbyt)uy6 database_name '

I have tested quite a lot and I found that the error is caused due to the special character in the password. Since I am getting the password from the .my.cnf file I am unable to escape it by hardcoding the escape characters.

Can anyone offer me a way to maybe search for those special characters in the $password variable and add to those escape slashes ("\").

EDIT: I forgot to mention that I am executing this via OpenVZ partial virtualization by using the vzctl exec command which is the reason why I needed a method which will allow me to escape the special characters as I have requested. The method I have developer was a simple use of the sed command:

sed 's/[!-+]/\\&/g' 

Thank you all for your help.

Best Regards!

Best Answer

You don't need to do any of this. As HBruijn mentioned in a comment, the $HOME/.my.cnf file already contains your credentials and MySQL's command line tools will use them automatically without you needing to do anything special.

So just do:

mysqldump $db |  ssh root@$destination_server "cat > /backup/mysql/$db.sql"