【问题标题】:Expand selected variables within here-document while invoking Bash through SSH通过 SSH 调用 Bash 时展开 here-document 中的选定变量
【发布时间】:2020-09-30 20:41:13
【问题描述】:

我没有远程访问 MySQL 服务器的权限,所以我尝试通过 SSH 会话进行。

它部分有效,但不正确。

sshpass -p $password ssh user@$IP /bin/bash << EOF
mysql -N -uroot -ppassword test -e "select id from client where user ='$user'"
EOF

这将显示 select 语句的结果,但我希望能够在另一个 echo 语句中使用该结果。

例如:

The user ID is: xxxxx

我尝试使用以下方法将输出分配给变量:

sshpass -p $password ssh user@$IP /bin/bash << EOF
res=$(mysql -N -uroot -ppassword test -e "select id from client where user ='$user'")
echo $res
EOF

但这会导致:

ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/run/mysql/mysql.sock' (2)

如果我像'EOF' 这样引用EOF,那么我可以将结果输入res,但我无法使用$user

有没有办法这样做,所以我可以在 heredoc 中使用我的变量并将 MySQL 查询的结果获取到一个新变量?

【问题讨论】:

标签: mysql bash ssh heredoc


【解决方案1】:

如果我像'EOF' 这样引用EOF,那么我可以将结果输入res,但我无法使用$user

您可以将$user 作为位置参数传递给bash,并且仍然具有引用的EOF 及其优势。例如:

sshpass -p "$password" ssh "user@$IP" /bin/bash -s "$user" << 'EOF'
res=$(mysql -N -uroot -ppassword test -e "select id from client where user ='$1'")
echo $res
EOF

Bash 手册对-s 选项的描述如下。

如果存在 -s 选项,或者如果选项处理后没有保留参数,则从标准输入读取命令。此选项允许在调用交互式 shell 或通过管道读取输入时设置位置参数。

【讨论】:

    猜你喜欢
    • 2015-12-08
    • 1970-01-01
    • 1970-01-01
    • 2015-01-31
    • 2016-05-22
    • 2011-04-13
    • 2020-05-28
    • 2016-12-08
    • 1970-01-01
    相关资源
    最近更新 更多