alnet
alnet

Reputation: 1233

Strange behaviour of bash script

I have the following script.sh:

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

When executing it as cat ./script.sh | bash I get

hello from server1

And when executing it as bash ./script.sh I get

hello from server1

hello from server2

Can anyone explain the difference? :)

Upvotes: 1

Views: 182

Answers (2)

Richard Kettlewell
Richard Kettlewell

Reputation: 616

In the first case the output of cat is connected to the standard input both of bash and of 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.

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.

Upvotes: 3

The Bndr
The Bndr

Reputation: 13394

you first example simply pipes the commands into the bash and does not care, if the 1st command is processed. (2nd command is swallowed by the bash)

Your 2nd example works, because the bash simply processed line by line.

//Update: the following should work in your first example:

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

Upvotes: 0

Related Questions