Minecraft Server Startup Script

A few friends from my gaming community “Cohesion of Wolfes” decided to create a small Minecraft server and I was tasked with the job of getting the backend running for now.

At first, we had a pretty basic and simple startup script that required you to have the Terminal or an SSH session open which was not very practical. So today I decided to take a 30min challenge to write a good, suitable script that runs the server in the background using the screen command.

#!/bin/bash
SERVER_JAR="spigot-1.15.1.jar"
Xms="1G"
Xmx="6G"

SCREEN_NAME="mc_server"

# change working directory to file location if not done yet
if [[ "${0%/*}" != "." ]] ; then
	pushd "${0%/*}"
fi

#------------------------------------------------

start_server() {
	echo "starting..."
	screen -d -m -U -S $SCREEN_NAME java -server -Xms$Xms -Xmx$Xmx -jar $SERVER_JAR
}

stop_server() {
	echo "stopping..."
	screen -S $SCREEN_NAME -X quit
}

restart_server() {
	stop_server
	sleep 5
	start_server
}

attach_server() {
	echo "attaching..."
	screen -d -r $SCREEN_NAME
}

#------------------------------------------------

if [[ $1 == "start" ]] ; then
	start_server
elif [[ $1 == "stop" ]] ; then
	stop_server
elif [[ $1 == "restart" ]] ; then
	restart_server
elif [[ $1 == "attach" ]] ; then
	attach_server
else 
	printf "\n\n"
	printf "HELP"
	printf "\n--------------------------\n\n"
	echo "Start the server:"
	echo "./${0##*/} start"
	printf "\n--------------------------\n\n"
	echo "Stop the server:"
	echo "./${0##*/} stop"
	printf "\n--------------------------\n\n"
	echo "Restart the server:"
	echo "./${0##*/} stop"
	printf "\n--------------------------\n\n"
	echo "Attach to console:"
	echo "./${0##*/}h attach"
	printf "\n\n"
fi

You can get the full script on Gitlab: https://gitlab.com/snippets/1967516


Configuration of the script

  • The script must be in the same folder as your server.jar file
  • Edit the following parameters to your needs
    • (lines 2 to 4)
    • SERVER_JAR contains the name of the file that contains the server application
    • Xms minimal heap size (should be at least 512M)
    • Xmx maximum heap size (should be at least 1G, recommended 2G or more)

Script Commands

CommandDescription
./startscript.sh startStarts the server
./startscript.sh stopStops the server
./startscript.sh restartRestarts the server
./startscript.sh attachAttach to the server console

Server console shortcuts

These only work while you have the server console open

ShortcutDescription
CTRL + A + DDetaches from the server console
CTRL + CStops the server

Disclaimer:
I know that the script is not perfect and that this can be done way better, like optimizing the Garbage Collector, etc. This was just what I had come up within less than 30min.