Ubuntu – Bash script and escaping special characters in password

bashpasswordscripts

I have been reading a lot of questions already asked here, however, somehow nothing is working for me. I have a bash script where I have to send password which dump database on remote machine, so its like :

!/bin/sh
/usr/bin/ssh -p 91899 user@remoteHost mysqldump -u db_user -p#8111*@uu( my_database |  gzip -c >  my_database.sql.gz

Now thing is that this password has all sorts of special character:
#8111*@uu(

If I run above command directly in shall using password inside single quotes then it works : ie.

/usr/bin/ssh -p 91899 user@remoteHost mysqldump -u db_user -p'#8111*@uu(' my_database |  gzip -c >  my_database.sql.gz

Without single quotes I get error with for the '(' at end.

I also tried to escape characters in password like this :

!/bin/sh
/usr/bin/ssh -p 91899 user@remoteHost mysqldump -u db_user -p'\#8111\*\@uu(' my_database |  gzip -c >  my_database.sql.gz

Then it gives access denied error.

I also tried to use "source" ie. saving password in another file as :

File pass.cre

MYPASSWORD='#8111*@uu('

Then including that file in bash script:

!/bin/sh
source pass.cre
/usr/bin/ssh -p 91899 user@remoteHost mysqldump -u db_user -p$MYPASSWORD my_database |  gzip -c >  my_database.sql.gz

It appears to be reading $MYPASSWORD from file then again error of invalid character.

Any advice what I am missing ?

Best Answer

Use double quotes twice, escaped and not escaped: -p"\"$MYPASSWORD\""

#!/bin/sh
source pass.cre
/usr/bin/ssh -p 91899 user@remoteHost 'mysqldump -u db_user -p"\"$MYPASSWORD\"" my_database |  gzip -c >  my_database.sql.gz'

Or an other version

/usr/bin/ssh -p 91899 user@remoteHost "mysqldump -u db_user -p\"'io#bc@14@9$#jf7AZlk99'\" my_database | gzip -c > my_database.sql.gz"

Examples

% source pass.cre
% ssh user@host mysqldump -u root -p$MYPASSWORD    
user@host's password: 
zsh:1: bad pattern: -p#8111*@uu(

% source pass.cre
% ssh user@host mysqldump -u root -p"$MYPASSWORD"   
user@host's password: 
zsh:1: bad pattern: -p#8111*@uu(

% source pass.cre
% ssh user@host mysqldump -u root -p"\"$MYPASSWORD\""
user@host's password: 
Warning: Using a password on the command line interface can be insecure.