4

This is my script, test.sh

if ssh myhost true; then
  echo 1
fi
echo 2

p.s. I have setup ssh key for myhost, so it won't ask password.

If I run it via bash, it will output two lines

$ bash test.sh
1
2

However, if I redirect the script to bash's stdin, it only output one line

$ bash < test.sh
1

Why do bash behave differently? Is this a bug of bash or a magic feature?

I have tried bash 4.3 and 4.4.

p.s. If I replace ssh myhost true with true, the script will always output two lines.

1
  • If you add -f to the ssh command, does it run both again? My test seems to run fine after that.
    – FCTW
    Commented Mar 31, 2017 at 18:27

1 Answer 1

3

Short answer: there's an important difference between having bash read commands from a file, and having bash take all input from a file.

ssh tends to read all available input from standard input, and send it over the connection to the remote computer. When you run bash test.sh, the shell reads commands from test.sh, but standard input is still your terminal; ssh will send anything you've typed ahead to the true command (which will ignore it). When you run bash < test.sh, standard input is set to the script, so both bash and the commands it runs read from that. bash reads the if block, then executes it; ssh reads the rest of the script (the echo 2 command), and sends it to the remote true, which ignores it. bash then finds that it's at the end of its input, so it exits.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .