Take the 2-minute tour ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems.. It's 100% free, no registration required.

This question already has an answer here:

If I use ssh to run some command in background, that command gets killed as soon an ssh hangs up:

ssh localhost -t "bash -c '(for i in 1 2 3 4 5; do sleep \$i;done)&'"; ps x|grep sleep

This will not show any running sleep process. (But it would, if I do the ps inside the ssh command.)

However if I manually log in, run it it background and logout, the command keeps running.

ssh localhost
bash -c '(for i in 1 2 3 4 5; do sleep $i;done)&';exit
ps x|grep sleep

Why is the first command killed? Why not the second one?

(NB: This problem arose when I tried to start a service with service tomcat start which worked fine after a manual login, but no service was running after invoking directly in the ssh command.)


No, this is not a duplicate of ssh + nohup does not work. I am not talking about nohup and I am not trying to use jobs instead of ps.

share|improve this question

marked as duplicate by Anthon, Timo, strugee, slm, Zelda Feb 11 at 17:55

This question has been asked before and already has an answer. If those answers do not fully address your question, please ask a new question.

    
No, this is not a duplicate of the mentioned question at all! –  michas Feb 11 at 19:19
add comment

1 Answer 1

It's your double quotes in the command

ssh localhost -t "bash -c '(for i in 1 2 3 4 5; do sleep $i;done)&'"

The shell which you are calling the command from tries to replace $i, before the whole commandline is executed. Usualy $i is not defined so it is interpreted to

ssh localhost -t "bash -c '(for i in 1 2 3 4 5; do sleep ;done)&'"

which runs through with 5 error messages saying

sleep: missing operand
Try 'sleep --help' for more information.

The solution is to mask the $ or to use outer single quotes:

ssh localhost -t "bash -c '(for i in 1 2 3 4 5; do sleep \$i;done)&'"
ssh localhost -t 'bash -c '\''(for i in 1 2 3 4 5; do sleep $i;done)&'\'
share|improve this answer
    
Oops, you are right. I was trying to set up a easy example and built in a totaly different bug. thanks for pointing out. Fixed this above. Now it shows the problem correctly. –  michas Feb 11 at 19:06
add comment

Not the answer you're looking for? Browse other questions tagged or ask your own question.