Saturday, June 1, 2019

ssh - why do bash behave differently for script from stdin?


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.


Answer



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.


No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...