通过SSH调用Bash时,在here-document中扩展所选变量 [英] Expand selected variables within here-document while invoking Bash through SSH
问题描述
我无法远程访问MySQL服务器,因此我正尝试通过SSH会话进行访问.
I don't have remote access to a MySQL server, so I am trying to do it via an SSH session.
部分可行,但无法正常运行.
It partly works, but not correctly.
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语句中使用该结果.
This will show the result of the select statement, but I'd like to be able to use that result in another echo statement.
例如:
The user ID is: xxxxx
我尝试使用以下命令将输出分配给变量:
I tried to assign the output to a variable using:
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
If I quote EOF like 'EOF'
then I can get the result into res
but I lose the ability to use $user
总有办法做到这一点,所以我可以在heredoc中使用我的变量,并将MySQL查询的结果获取到一个新变量中?
Is there anyway to do this so I can use my variable in the heredoc and get the result of the MySQL query to a new variable ?
推荐答案
如果我像
'EOF'
这样引用EOF,则可以将结果输入res
,但是我失去了使用$ user
的能力
If I quote EOF like
'EOF'
then I can get the result in tores
but I lose the ability to use$user
您可以将 $ user
传递给bash作为位置参数,并且仍然具有引号EOF及其优点.例如:
You can pass $user
to bash as a positional parameter and still have the quoted EOF and its advantages. E.g:
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
选项,如下所示.
Bash manual describes the -s
option as follows.
如果存在-s选项,或者在选项处理后没有剩余参数,则然后从标准输入中读取命令.此选项允许在调用交互式外壳或通过管道读取输入时设置位置参数.
If the -s option is present, or if no arguments remain after option processing, then commands are read from the standard input. This option allows the positional parameters to be set when invoking an interactive shell or when reading input through a pipe.
这篇关于通过SSH调用Bash时,在here-document中扩展所选变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!