I have a script that takes a while to run, and I'm using screen to run it.

ssh user@host screen -dm "python dostuff.py"

Now the question is, how do I make sure it kills the screen session after dostuff.py finishes execution? Whether it's because an error, or proper termination.

  • 1
    Having screen close is the default behavior I see, is yours staying open? Mar 1, 2016 at 17:40
  • @EricRenouf yes, after the script finishes executing, I have to manually go back there, attach it back to my screen, and exit from it.
    – Shelby. S
    Mar 1, 2016 at 17:42
  • I also get a detached screen; even tried screen -dm "ls;exit"
    – Jeff Schaller
    Mar 1, 2016 at 17:43
  • 1
    What version of screen are you guys using? I'm not able to recreate that, and all my quick searching turns out people trying to figure out how to prevent screen from terminating as soon as the command it's running finishes (e.g., here or here or even here Mar 1, 2016 at 18:08
  • 1
    Unable to replicate @JeffSchaller's experiment. screen -S foo -dm "sleep 10" followed by screen -ls will show a screen named foo for ten seconds; it then disappears. Doing the same to invoke a python script that uses time.sleep(10) behaves the same- the screen is terminated when the script is completed. This is with Screen version 4.00.03 (FAU).
    – DopeGhoti
    Mar 1, 2016 at 18:22

1 Answer 1


This might be in the "workaround" category, but I was able to achieve what I think your goal is by putting the command ("python dostuff.py" from your example) into a shell script, then running ... screen -d -m "/path/to/that/script"

Version info:

$ screen -v
Screen version 3.09.10 (FAU) 4-Sep-01

Looks like I have a pretty old version of screen on this system! Perhaps screen's behavior changed in more recent versions to automatically exit?

$ screen -ls
No Sockets found in /tmp/uscreens/S-username.
$ screen -dm "ls"
$ screen -ls
There is a screen on:
        32112694.ls     (Detached)
1 Socket in /tmp/uscreens/S-username.

(screen -r; exit)

$ screen -ls
No Sockets found in /tmp/uscreens/S-username.

$ cat runme
sleep 6
ls > now

$ screen -d -m ./runme
$ ps -ef|grep sleep
 username 9633926  9437204   0 14:55:23  pts/1  0:00 grep sleep
 username 15532242 10223670   0 14:55:21  pts/6  0:00 sleep 6

(wait 6 seconds)

$ screen -ls
No Sockets found in /tmp/uscreens/S-username.
$ ls now

One thing I realized when going through this was that my version of screen seemed to expect a session name after -dm; I had to separate -d and -m in order to pass a command argument.

Try using:

ssh user@host screen -d -m python dostuff.py

with an optional -S to name the session something specific.

  • Yup, turns out splitting -d and -m solved it for. That's weird.
    – Shelby. S
    Mar 1, 2016 at 21:23

You must log in to answer this question.

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