简体   繁体   English

bash脚本的奇怪行为

[英]Strange behaviour of bash script

I have the following script.sh: 我有以下script.sh:

#!/bin/bash
ssh server1 "echo hello from server1"
ssh server2 "echo hello from server2"

When executing it as cat ./script.sh | bash cat ./script.sh | bash身份执行时cat ./script.sh | bash cat ./script.sh | bash I get cat ./script.sh | bash我得到

hello from server1 来自server1的问好

And when executing it as bash ./script.sh I get 当以bash ./script.sh执行它时

hello from server1 来自server1的问好

hello from server2 来自server2的问好

Can anyone explain the difference? 谁能解释其中的区别? :) :)

In the first case the output of cat is connected to the standard input both of bash and of ssh. 在第一种情况下,cat的输出连接到bash和ssh的标准输入。 ssh reads from its stdin, therefore consuming the rest of the output of cat, although in this case the result is discarded since the remote command never itself reads stdin. ssh从其stdin读取,因此消耗了cat的其余输出,尽管在这种情况下,由于远程命令本身从未读取stdin,结果被丢弃了。

In the second case the stdin for bash, and therefore ssh, is your terminal, and bash opens the script file separately, so ssh does not get to see it. 在第二种情况下,bash的stdin(即ssh)是您的终端,bash单独打开脚本文件,因此ssh看不到它。

you first example simply pipes the commands into the bash and does not care, if the 1st command is processed. 您的第一个示例只是将命令通过管道传送到bash中,而无需关心是否处理了第一个命令。 (2nd command is swallowed by the bash) (第二个命令被bash吞没了)

Your 2nd example works, because the bash simply processed line by line. 您的第二个示例有效,因为bash只是逐行处理。

//Update: the following should work in your first example: //更新:以下内容将在您的第一个示例中起作用:

#!/bin/bash
ssh server1 "echo hello from server1" &
ssh server2 "echo hello from server2" &

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

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