简体   繁体   English

为什么在此bash脚本中执行顺序相反?

[英]Why is the order of execution inversed in this bash script?

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 , 通过SSH连接到服务器,
  2. then change to the folder www , 然后转到文件夹www
  3. then store the tail of index.htm into the variable var 然后将index.htm尾部存储到变量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. 相反,似乎tail是在更改文件夹之前执行的,因此找不到index.htm文件。

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. 我尝试使用不同的命令,并且每次似乎我尝试存储到变量中的命令替换结果在打开SSH连接后,在执行任何其他脚本之前都立即执行。

What am I missing here ? 我在这里想念什么?

The $(...) is being expanded locally, before the contents of the here document are passed to ssh . $(...)在本地扩展,然后将here文档的内容传递给ssh To send literal text to the remote server, quote the here document delimiter. 要将文字文本发送到远程服务器,请引用此处文档定界符。

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

(Also, quote the expansion of $var to protect any embedded spacing from the shell.) (另外,引用$var的扩展名以保护外壳程序的任何嵌入式间距。)

The tail is running in the bash script on your local machine, not on the remote host. tail在本地计算机上的bash脚本中运行,而不是在远程主机上。 The substitution is getting made before you even execute the ssh command. 甚至在执行ssh命令之前都会进行替换。

Your script can be replaced with simply: 您的脚本可以简单地替换为:

ssh -T user@$123.456.789.123 tail www/index.htm

If you want to send those commands to the remote server, you can write 如果要将这些命令发送到远程服务器,可以编写

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

Note that conditioning the next command on the result of the previous allows SSH to return a meaningful return code. 请注意,根据前一个命令的结果限制下一个命令,可使SSH返回有意义的返回码。 In your heredoc, whatever happens (eg tail fails), SSH will return with $?=0 because echo will not fail. 在您的Heredoc中,无论发生什么情况(例如, tail失败),SSH都将以$?= 0返回,因为echo不会失败。

Another option is to create a script there and launch it with ssh. 另一种选择是在此处创建脚本并使用ssh启动它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM