4

This question already has an answer here:

I'm launching a process in a named screen like:

screen -dmS myscreen bash -c "export VAR=123; cd /usr/local/myproject; ./myscript.py"

However, after a few minutes, my script crashes and when it exits the screen terminates so I can't see the debugging output. My script runs long enough so I can manually attach to the screen, but the screen still auto-terminates kicking me out of it.

How do I stop the screen from exiting when the process it's running stops?

marked as duplicate by Jeff Schaller, Archemar, Anthon, Jakuje, MelBurslan Apr 25 '16 at 18:42

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.

5

You can pipe the output to less or a file with tee and then to less, or just add a "pause" command like sleep 99999 after the command.

screen -dmS myscreen bash -c "export VAR=123; cd /usr/local/myproject; ./myscript.py; sleep 9999"

In any case i recommend switching from screen to tmux, and you can use this question to learn how to run a command and leave it after it exit.

basically you can add bash -i to the end of your command.

tmux start-server  
tmux new-session -d
tmux new-window 'ls;bash -i'

or you can use the this option remain-on-exit

set-remain-on-exit [on | off]

When this option is true, windows in which the running program has exited do not close, instead remaining open but inactivate.

  • 2
    This seems like an unreliable hack. If I create the screen manually and detach, it doesn't terminate. What's the difference between that and the screen I create without attaching? – Cerin Sep 28 '14 at 14:59
1

By default, screen exits when the command it is running closes, as you've observed. When you start screen by itself, the command it runs is an interactive shell, which of course doesn't exit when its children do.

If you want to be able to achieve something like this from another script, you could do

screen -dm -S myscreen
screen -S myscreen -X stuff "export VAR=123; cd /usr/local/myproject^M"
screen -S myscreen -X stuff "./myscript.py && exit^M"

This first starts a new screen which will have a login shell running in it and will not close until the login shell exits. You then use screen's stuff command to input text into that shell. On the first line, we define the variables and change directory. On the second line, we start the script, and then exit the shell (assuming here that you want to close the screen session if the script succeeds). However, due to the short-circuit and (&&), if myscript.py fails, the exit will never happen, and you'll be free to reconnect to the screen session and see what happened.

Note that to input the ^M properly, you need to type ^V (control-v) followed by ^M (which is the same as your enter key).

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