1

I have this script :

ssh -T user@$123.456.789.123 <<EOF

    cd www

    var=$(tail index.htm)

    echo $var

EOF

What I thought it should do is :

  1. Connect to the server through SSH,
  2. then change to the folder www,
  3. then store the tail of index.htm into the variable var
  4. and finally echo the result.

Instead it seems that tail is executed before the change of folder, and thus doesn't find the index.htm file.

I've tried with different commands, and each time it seems the result from command substitution I'm trying to store into a variable is executed right after the SSH connexion is opened, before any other piece of script.

What am I missing here ?

4

3 回答 3

3

$(...)将此处文档的内容传递给ssh. 要将文字文本发送到远程服务器,请引用此处的文档分隔符。

ssh -T user@$123.456.789.123 <<'EOF'
    cd www
    var=$(tail index.htm)
    echo "$var"
EOF

(另外,引用扩展$var以保护外壳的任何嵌入间距。)

于 2013-10-16T18:17:06.733 回答
2

tail在本地机器上的 bash 脚本中运行,而不是在远程主机上。甚至在您执行ssh命令之前就进行了替换。

您的脚本可以简单地替换为:

ssh -T user@$123.456.789.123 tail www/index.htm
于 2013-10-16T18:16:19.163 回答
2

如果要将这些命令发送到远程服务器,可以编写

ssh -T user@$123.456.789.123 'cd www && var=$(tail index.htm) && echo $var'

请注意,根据上一个命令的结果调节下一个命令允许 SSH 返回一个有意义的返回码。在您的heredoc 中,无论发生什么(例如tail失败),SSH 都会返回 $?=0 因为echo不会失败。

另一种选择是在那里创建一个脚本并使用 ssh 启动它。

于 2013-10-16T18:23:40.323 回答