Ubuntu – Run a script on boot

bashscriptsstartupsystemd

I have a script to start a java application automatically.

# colors
red='\e[0;31m'
green='\e[0;32m'
yellow='\e[0;33m'
reset='\e[0m'

echoRed() { echo -e "${red}$1${reset}"; }
echoGreen() { echo -e "${green}$1${reset}"; }
echoYellow() { echo -e "${yellow}$1${reset}"; }

# Check whether the application is running.
# The check is pretty simple: open a running pid file and check that the process
# is alive.
isrunning() {
  # Check for running app
  if [ -f "$RUNNING_PID" ]; then
    proc=$(cat $RUNNING_PID);
    if /bin/ps --pid $proc 1>&2 >/dev/null;
    then
      return 0
    fi
  fi
  return 1
}

start() {
  if isrunning; then
    echoYellow "Test App Already Running"
    return 0
  fi

  pushd $APPLICATION_DIR > /dev/null
  nohup java -jar *.jar>test.out 2>test.err &
  echo $! > ${RUNNING_PID}
  popd > /dev/null

  if isrunning; then
    echoGreen "Test Application started"
    exit 0
  else
    echoRed "The Test Application has not started - check log"
    exit 3
  fi
}

restart() {
  echo "Restarting Test Application"
  stop
  start
}

stop() {
  echoYellow "Stopping Test Application"
  if isrunning; then
    kill `cat $RUNNING_PID`
    rm $RUNNING_PID
  fi
}

status() {
  if isrunning; then
    echoGreen "Test Application is running"
  else
    echoRed "Test Application is either stopped or inaccessible"
  fi
}

case "$1" in
start)
    start
;;

status)
   status
   exit 0
;;

stop)
    if isrunning; then
        stop
        exit 0
    else
        echoRed "Application not running"
        exit 3
    fi
;;

restart)
    stop
    start
;;

*)
    echo "Usage: $0 {status|start|stop|restart}"
    exit 1
esac

refer:- https://vertx.io/blog/vert-x-3-init-d-script/

when I run this command using sudo service test start, working fine. I want to run this automatically on boot up. I tried to creating test.service file on /etc/systemd/system. When I run services not starting.

[Unit]
Description=Test service
After=network.target
StartLimitIntervalSec=0

[Service]
Type=simple
Restart=always
RestartSec=1
User=test
ExecStart=/etc/init.d/test start

[Install]
WantedBy=multi-user.target

What is wrong with this?

Best Answer

You don't need to write systemd script test.service to enable init.d script on boot. If your init.d script is already working fine, you just need to enable your init.d script to run on boot by following commands.

sudo update-rc.d test defaults
sudo update-rc.d test enable
Related Question