How to Control Systemd Service Using Screen

bashgnu-screen

I've set up a systemd service to run my Minecraft server. Now, I need it to repeat the start script when the server crashes.
Here's my code so far:

#!/bin/bash

while true; do
    cd /home/mcserver/Spigot
    echo Starting Spigot...
    echo 600 > ./restart-info
    java -jar spigot.jar
    echo Server has stopped or crashed, starting again in 5 minutes...
    sleep 300
done

I can actually view the output of spigot.jar using systemctl status spigot, but I also want to control the server console, maybe using screen.

When I try to do this:

screen -S "Spigot" java -jar spigot.jar

I'll get the Must be connected to a terminal error. This command only works in a terminal (not in a script) and I can attach it using screen -r.

Is there any way to "bypass" this screen bug?
I already tried to place script /dev/null before the screen command.
I don't want to use screen with -d and -m because it'll run in the background and the script will keep restarting my server.

Best Answer

I don't want to use screen with -d and -m because it'll run in the background and the script will keep restarting my server.

So use -D instead of -d (note the capital case!)

-D -m This also starts screen in "detached" mode, but doesn't fork a new process. The command exits if the session terminates.

As screen won't fork a new process, it will block while java is running, and exit when the server stops.

As a bonus, if you add -S spigot you can monitor the output (and even send commands!) from any terminal by attaching to that screen

And... since you're using a systemd service anyway (and you should indeed), why are you doing this restart loop in your script? Let systemd handle that for you using Restart=always and RestartSec=5min

Related Question