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).