How can I script GNU Screen to start with a program running inside of it so that it does not exit the session when the program completes?
I want to run an interactive program as a daemon, if I manually start screen and then launch this program inside of it everything works just as I want. If the program exits or crashes the screen session remains and I can go look at it to see what just happened. However, if I start the program with a simple screen launch then it does run inside of screen but when the program exits the screen session ends and any output from the program is lost.
So screen –dmS serverName serverApplication
does not work for my scenario. I did think about making a script which launches the program I want to run & then sleeps forever, I could then launch the script at the same time as screen and should get the effect I am after but it seems rather an untidy way to do things and I am sure there must be something more elegant.
I have read quite a few screen tutorials and trawled through the man page but nothing leaps out at me as the right way to do this. I did try –X but that is for screen commands, not for running commands inside the screen session... Any suggestions will be very much appreciated; I am even happy to use something other than GNU Screen if there is a better tool for use in scripting but please give me an example where possible.
(Side note: The two things I will be running with this are a minecraft_server and a mythtv_backend. My plan was to launch these from a chron job at boot via some ruby/bash script)
First, you'll want to start a daemon screen session just running your default shell:
$ screen -dmS "serverName"
Then, send your command to that shell using screen's stuff
in combination with -X
:
$ screen -S "serverName" -p 0 -X stuff "serverApplication$(printf \\r)"
The -p
is important for telling screen into which window within that session to stuff the command. In this case, it's the only available window, 0, but if you don't specify that, for some odd reason your command will go nowhere. The $(printf \\r)
sends a 'Return' keystroke. A regular \n
might work in its place, but I've read that's shell-dependent. The newline character does not work in bash; I can vouch for that.
Here's another cool trick. If you want to then make another screen window within that session, you can:
$ screen -S "serverName" -X screen
Now you can send commands to that one using the same syntax as above, but with -p 1
. Lots of fun.