Bash subshell very weird behavior with ssh command

2020-04-18 01:57发布

问题:

Consider script s2:

#!/bin/bash
ssh localhost tail

And script s1

#!/bin/bash
./s2 &
sleep 1000
wait

Now call s1. It won't call the ssh command.

If you remove the & in s1 it will. If you call ./s2 directly it will. If you type in the console ./s2 & it will.

But ./s1 won't work. Why ?

回答1:

I don't know for me it does not call the ssh command. If i remove the sleep then it exits immediately.

Sure it calls the ssh command. It has to! There's no magic.

It's a big mistake to assume that just because the script exits immediately when you remove sleep, it is not calling ssh. That conclusion is incorrect. There can be other reasons to explain this observed behavior.

If you wanted to verify that ssh did not run, one way to do that would be to look at your system logs.

The script exits very soon (not immediately) because ssh exits very soon. When s2 runs, it receives empty stdin, which the tail command consumes and outputs nothing, and so the ssh shell terminates without any output. That's all.

Change s2 to this to see the difference:

#!/bin/bash
ls / | ./s2 &
wait

This way s2 will have a non-empty stdin to work with, and should produce some output.

Btw the sleep 1000 was unnecessary from the beginning, thanks to the wait.