如何将包含特殊字符的参数传递给 bash 脚本?

How do I pass arguments containing special characters to a bash script?

通常我可以在我的服务器中以下列方式通过命令行向 运行 一个 sql 脚本 运行 命令:

[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

所以我想让它变得简单并为我准备一个 bash 脚本 运行:

#!/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}"

我的结果如下:

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.

我也知道 bash 中有一些特殊字符,所以我也尝试了以下方法(通过在特殊字符前加上 \):

#!/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}"

输出是:

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

(我已经模糊了一些值,显然是出于某些安全原因。)

不要尝试手动执行 shell 引用:让 shell 为您完成。

因此,如果您有有效的本地命令:

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

...然后将其封装在一个函数中,方法是在前面添加 mycmd() { 行,在后面添加 } 行:

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
}

...并告诉 shell 将该函数序列化到您的 ssh 会话中:

ssh test_server "$(declare -f mycmd); mycmd"