在启动时运行脚本

在启动时运行脚本

我有一个可以自动启动 java 应用程序的脚本。

# 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

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

当我使用 运行此命令时sudo service test start,运行正常。我想在启动时自动运行它。我尝试test.service在 上创建文件/etc/systemd/system。当我运行时,服务没有启动。

[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

这有什么问题?

答案1

您无需编写 systemd 脚本test.service来在启动时启用 init.d 脚本。如果您的 init.d 脚本已经正常工作,您只需要按照以下命令启用 init.d 脚本在启动时运行。

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

相关内容