0

Normally I can run a command to run a sql script via the commandline in the following manner in my server:

[ec2-user@ip-XX-XX-XX-XXX ~]$ sudo mysql -h BLAHBLAHBLAH.us-east-1.rds.amazonaws.com -u user -p'aaaaa:b>c[d{e]ff=|ggggggggg^$*' adi_chf_db < ./test.sql

So I wanted to make this simple and have a bash script run it for me:

#!/bin/bash

sql_cmd_to_run="sudo mysql -h BLAHBLAHBLAH.us-east-1.rds.amazonaws.com -u user -p\'aaaaa:b>c[d{e]ff=|ggggggggg^$*\' test_database < ./test.sql"
ssh -t test_server "${sql_cmd_to_run}"

My result is the following:

bash: ggggggggg^': command not found
ERROR 1045 (28000): Access denied for user 'user'@'XX.XX.XX.XXX' (using password: YES)
Connection to XX.XX.XX.XXX closed.

I also understand that there are some special characters in bash so I tried the following as well (by putting \ before the special characters):

#!/bin/bash

sql_cmd_to_run="sudo mysql -h BLAHBLAHBLAH.us-east-1.rds.amazonaws.com -u user -p\'aaaaa:b\>c\[d\{e\]ff=\|ggggggggg\^$\*\' test_database < ./test.sql"
ssh -t test_server "${sql_cmd_to_run}"

Which the output is:

ERROR 1045 (28000): Access denied for user 'user'@'XX.XX.XX.XXX' (using password: YES)
Connection to XX.XX.XX.XXX closed.

(I've obscured some of the values, obviously for some security reasons.)

Inigo
  • 12,186
  • 5
  • 41
  • 70
user352258
  • 45
  • 3
  • 10
  • please don't tag spam. It inserts your question into search results where it doesn't belong. – Inigo Jul 07 '21 at 01:13

1 Answers1

2

Don't try to do shell quoting by hand: Let the shell do it for you.

So, if you have a working local command:

sudo mysql -h BLAHBLAHBLAH.us-east-1.rds.amazonaws.com -u user -p'aaaaa:b>c[d{e]ff=|ggggggggg^$*' adi_chf_db < ./test.sql

...then encapsulate it in a function, by adding a mycmd() { line before and a } line after:

mycmd() {
  sudo mysql -h BLAHBLAHBLAH.us-east-1.rds.amazonaws.com -u user -p'aaaaa:b>c[d{e]ff=|ggggggggg^$*' adi_chf_db < ./test.sql
}

...and tell the shell to serialize that function into your ssh session:

ssh test_server "$(declare -f mycmd); mycmd"
Charles Duffy
  • 280,126
  • 43
  • 390
  • 441
  • Hey that's a neat trick :) , it saves me the time of having to deal with those pesky special characters haha. – user352258 Jul 07 '21 at 01:25