How do I automatically restart a Minecraft Spigot server in the event of a crash or /stop when using screen?

Tutorial

A friend wrote a bash script to automatically restart a minecraft (spigot) server in the event of a crash or with the command “/stop” when using screen. There are several seconds to cancel the restart with Enter. In addition, the exit codes of the previous session are written to a file, which can be used to understand when and why a server has crashed or restarted.

You need two files:

  1. “start.sh”
#!/bin/sh

screen -d -m -S "mc_spigot_server" ./startserver.sh

  1. “startserver.sh”
#!/bin/bash

JAR=spigot-1.15.2.jar
MAXRAM=1024M
MINRAM=1024M
TIME=20


while [ true ]; do
    java -Xmx$MAXRAM -Xms$MINRAM -jar $JAR nogui
    if [[ ! -d "exit_codes" ]]; then
        mkdir "exit_codes";
    fi
    if [[ ! -f "exit_codes/server_exit_codes.log" ]]; then
        touch "exit_codes/server_exit_codes.log";
    fi
    echo "[$(date +"%d.%m.%Y %T")] ExitCode: $?" >> exit_codes/server_exit_codes.log
    echo "----- Press enter to prevent the server from restarting in $TIME seconds -----";
    read -t $TIME input;
    if [ $? == 0 ]; then
        break;
    else
        echo "------------------- SERVER RESTARTS -------------------";
    fi
done

You can change the start parameters by changing the variables:

JAR = server filename

MAXRAM = maximum RAM

MINRAM = minimum RAM

TIME = time in seconds until server restarts automatically

Execute the following in the directory:

chmod +x start.sh startserver.sh

Run your start up script:

./start.sh
  • To leave the minecraft screen press Ctrl + A + D
  • To reconnect to minecraft screen use screen -r

Did you discover any mistakes or do you disagree? Help me do it better.

Leave a Comment