Skip to content

Instantly share code, notes, and snippets.

@asidko
Last active October 28, 2024 11:50
Show Gist options
  • Save asidko/206a4705429d25b956213d4eb431bc29 to your computer and use it in GitHub Desktop.
Save asidko/206a4705429d25b956213d4eb431bc29 to your computer and use it in GitHub Desktop.
A simple application runner for managing the start/stop operations of binary executables on a Linux virtual machine (VM)
#!/bin/bash
##################################################
# Run script for applications
# Usage: ./run.sh start
# ./run.sh restart
# ./run.sh stop
# Features:
# - Auto-detect application name and port (based on folder name) and binary (last by creation date)
# - Automatically checks if the application is running, shows its last logs
##################################################
# General variables (no need to change)
APP_NAME=$(basename "$(pwd)") # as a directory name
APP_PORT=$((8000 + (0x$(echo -n "$APP_NAME" | md5sum | awk '{print $1}' | cut -c1-8) % 1001))) # 8000-9000 based on the app name hash
LOG_FILE="log-${APP_NAME}.txt"
PID_FILE="${APP_NAME}.pid"
# Pick up variables from .env file if exists
[ -f .env ] && export $(grep -v '^#' .env | xargs)
# ❗️ Application specific variables, make sure to change them
BIN=$(find . -maxdepth 1 -type f -name "*.jar" | sort -nr | head -n 1) || { echo "ERROR: Binary not found!"; exit 1; } # last by creation date
CMD="java -jar '$BIN' --server.port=$APP_PORT"
# General functions (no need to change)...
start() {
if [ -f "$PID_FILE" ] && ps -p "$(cat "$PID_FILE")" > /dev/null 2>&1; then
echo "⚠️ Application $APP_NAME is already running."
exit 1
fi
echo "Application $APP_NAME is starting..."
echo "🚀 Command: $CMD"
nohup bash -c "$CMD" >> "$LOG_FILE" 2>&1 &
echo $! > "$PID_FILE"
sleep 3
logs
check
}
stop() {
if [ ! -f "$PID_FILE" ]; then
echo "PID file not found."
exit 1
fi
PID=$(cat "$PID_FILE")
kill "$PID"; sleep 2
ps -p "$PID" > /dev/null 2>&1 && kill -9 "$PID"
rm -f "$PID_FILE"
echo "🛑 Application $APP_NAME stopped."
}
restart() {
stop
start
}
logs() {
if [ -f "$LOG_FILE" ]; then
tail -n 100 "$LOG_FILE"
echo "📔 To watch logs in real-time: tail -f $LOG_FILE -n 500"
else
echo "⚠️ Log file not found."
fi
}
check() {
if [ -f "$PID_FILE" ]; then
PID=$(cat "$PID_FILE")
if ps -p "$PID" > /dev/null 2>&1; then
echo "✅ Application $APP_NAME is running with PID $PID."
else
echo "⚠️ Application $APP_NAME is not running, but PID file exists."
fi
else
echo "🛑 Application $APP_NAME is not running."
fi
}
case "$1" in
start)
start
;;
stop)
stop
;;
restart)
restart
;;
logs)
logs
;;
check)
check
;;
*)
echo "Usage: $0 {start|stop|restart|logs|check}"
exit 1
;;
esac
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment