通过 SSH 调用 Bash 时展开此处文档中的选定变量
Expand selected variables within here-document while invoking Bash through SSH
我无法远程访问 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 查询的结果获取到新变量?
If I quote EOF like 'EOF'
then I can get the result in to res
but I lose the ability to use $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 =''")
echo $res
EOF
Bash手册对-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.
我无法远程访问 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 查询的结果获取到新变量?
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及其优点。例如:
sshpass -p "$password" ssh "user@$IP" /bin/bash -s "$user" << 'EOF'
res=$(mysql -N -uroot -ppassword test -e "select id from client where user =''")
echo $res
EOF
Bash手册对-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.