Skip to content

Instantly share code, notes, and snippets.

@jarryDk
Last active January 8, 2022 09:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jarryDk/5c316794da43a63a826124e77020ebdb to your computer and use it in GitHub Desktop.
Save jarryDk/5c316794da43a63a826124e77020ebdb to your computer and use it in GitHub Desktop.
Script will restart a Minecraft server after a Crash and in the process remove pid created by the script, remove ./world/session.lock and kill old process if still running.
#!/bin/bash
MINECRAFT_VERSION=1.18.1
set -euo pipefail
cd ${0%/*}
PIDFILE=./minecraft.pid
SESSION_LOCK=./world/session.lock
GREEN='\033[0;32m'
RED='\033[0;31m'
NC='\033[0m' # No Color
function restart() {
echo -e "${RED}------------------------------------------------------${NC}" | tee -a start-server-with-pid.log
echo -e "${RED}Getting ready to restart Minecraft version : $MINECRAFT_VERSION${NC}" | tee -a start-server-with-pid.log
echo -e "${RED}Minecraft crached at $(date +'%Y-%m-%d %H:%M:%S')${NC}" | tee -a start-server-with-pid.log
if [[ -f $PIDFILE ]]; then
echo -e "${RED} - Remove the file $PIDFILE as part of restart${NC}" | tee -a start-server-with-pid.log
rm $PIDFILE
fi
if [[ -f $SESSION_LOCK ]]; then
echo -e "${RED} - Remove the file $SESSION_LOCK as part of restart${NC}" | tee -a start-server-with-pid.log
rm $SESSION_LOCK
fi
PID_OF_PORT_IN_USE=$(lsof -i:25565 | grep LISTEN | awk '{print $2}')
if [[ "X" != "X$PID_OF_PORT_IN_USE" ]]; then
echo -e "${RED} - Kill existing Minecraft server running on port 25565 as part of restart${NC}" | tee -a start-server-with-pid.log
kill -9 $PID_OF_PORT_IN_USE
fi
echo -e "${RED}------------------------------------------------------${NC}" | tee -a start-server-with-pid.log
exec "./start-server-with-pid.sh"
}
# PID file
if [[ -f $PIDFILE ]]; then
pid=$(cat $PIDFILE)
ps -p $pid > /dev/null 2>&1
if [ $? -eq 0 ]; then
echo "Minecraft is already running" | tee -a start-server-with-pid.log; exit 1
else
# process not found, overwrite
echo $$ > $PIDFILE;
fi
else
# wasn't running, write pid
echo $$ > $PIDFILE;
fi
# after PID file has been set
trap restart EXIT
export JAVA_HOME="/opt/java/jdk-17.0.1+12"
echo "" | tee -a start-server-with-pid.log
echo -e "${GREEN}Getting ready to start Minecraft version : $MINECRAFT_VERSION${NC}" | tee -a start-server-with-pid.log
echo -e "${GREEN}Minecraft starting at $(date +'%Y-%m-%d %H:%M:%S')${NC}" | tee -a start-server-with-pid.log
echo "JAVA_HOME : $JAVA_HOME" | tee -a start-server-with-pid.log
echo "" | tee -a start-server-with-pid.log
$JAVA_HOME/bin/java -Xmx2048M -Xms2048M -jar server_$MINECRAFT_VERSION.jar nogui
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment