0

I am used to using linux terminals and nohup over ssh to issue commands that run in the background even when logged out of the ssh session. For some reason nohup seems to be broken in the latest MACOS. For that reason I am trying to executing this small sample script using screen command.

sleep 10
echo "this is my test file" > testfile

This file is saved as tst script. And then I issue the following command.

ssh sohaib@localhost screen -dm sh testscript

However nothing happens. screen just exits quietly without writing to the file testfile. If I run this without ssh it works as desired. What am I doing wrong here?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
Sohaib
  • 4,556
  • 8
  • 40
  • 68

1 Answers1

0

The issue is that after your script exits the screen exits. The -dm is for deamons, i.e., scripts that keep running.

Showing the screen exiting after 10 seconds:

On remote host (file is executable):

ttucker@merlin:~$ cat test.sh 
#!/bin/bash
echo derp > /tmp/test.txt
sleep 10

Command on local machine:

[ttucker@localhost ~]$ ssh ttucker@merlin 'screen -dmS my_screen ~/test.sh'

After run.

On remote machine, a few seconds after screen is running:

ttucker@merlin:~$ screen -ls
There is a screen on:
    23141.my_screen (11/21/2016 07:05:11 PM)    (Detached)
1 Socket in /var/run/screen/S-ttucker.

On remote machine, over 10 seconds later:

ttucker@merlin:~$ screen -ls
No Sockets found in /var/run/screen/S-ttucker.

Modifying the script to keep running, and so, keeping the screen up:

If you are really running a script that needs to stay up you can do the following in the script:

#!/bin/bash
while true; do
    # Do something
    sleep 10
done

This will do something, wait 10 seconds, then loop again.

Or, detaching the screen manually:

You can ssh to the remote machine, run screen, then press Ctrl+A,D, press Ctrl and hold, then hit A then hit D. You can now exit the SSH session and the screen will stay running.

Tim
  • 2,139
  • 13
  • 18
  • Thanks for the answer. I suppose I wrote my question wrong. The screen exiting is not a problem. Even in such a scenario the test file should have the text that I echo. This test with local machine is just to make things simpler. My actual objective is to start a java service on a remote host. And I want to do this using a script so logging in does not help of course. – Sohaib Nov 21 '16 at 20:07
  • In my test, the file does have the text in it. I also noticed that my quoting was different from yours. Also, I put a `#!` at the top of my script file, made it executable, and called it with `./testscript` - try changing that instead of calling it with `sh testscript`. Also, If you are wondering, the `#!/bin/bash` tells the script what executable to run when it is called. – Tim Nov 21 '16 at 20:14