开源项目 init-script-template
使用教程
项目介绍
init-script-template
是一个用于创建自定义初始化脚本的模板项目。该项目提供了一个基本的初始化脚本模板,可以帮助用户快速地创建自己的初始化脚本。用户可以根据需要修改这个模板,并将其应用于各种系统和应用中。
项目快速启动
要使用 init-script-template
,您首先需要将该项目克隆到本地计算机上:
git clone https://github.com/fhd/init-script-template.git
然后,在项目目录中,您可以根据自己的需求修改 init.sh
文件中的代码。例如,您可以添加或删除变量、更改脚本的行为等等。
最后,您可以将修改后的 init.sh
脚本复制到您需要的地方,并运行该脚本来初始化您的系统或应用。
应用案例和最佳实践
应用案例
假设您需要在启动时自动运行一个 Node.js 应用,您可以使用 init-script-template
来创建一个初始化脚本。以下是一个简单的示例:
-
克隆项目并进入目录:
git clone https://github.com/fhd/init-script-template.git cd init-script-template
-
修改
init.sh
文件,添加 Node.js 应用的启动命令:#!/bin/bash ### BEGIN INIT INFO # Provides: mynodeapp # Required-Start: $local_fs $network $named $time $syslog # Required-Stop: $local_fs $network $named $time $syslog # Default-Start: 2 3 4 5 # Default-Stop: 0 1 6 # Description: Start My Node.js App ### END INIT INFO dir="/path/to/your/node/app" cmd="node app.js" user="yourusername" name=$(basename "$0") pid_file="/var/run/$name.pid" log_file="/var/log/$name.log" get_pid() { cat "$pid_file" } is_running() { [ -f "$pid_file" ] && ps $(get_pid) > /dev/null 2>&1 } case "$1" in start) if is_running; then echo "Already started" else echo "Starting $name" cd "$dir" if [ -z "$user" ]; then sudo $cmd >> "$log_file" 2>&1 & else sudo -u "$user" $cmd >> "$log_file" 2>&1 & fi echo $! > "$pid_file" if ! is_running; then echo "Unable to start, see $log_file" exit 1 fi fi ;; stop) if is_running; then echo -n "Stopping $name.." kill $(get_pid) for i in {1..10} do if ! is_running; then break fi echo -n "." sleep 1 done echo if is_running; then echo "Not stopped; may still be shutting down or shutdown may have failed" exit 1 else echo "Stopped" if [ -f "$pid_file" ]; then rm "$pid_file" fi fi else echo "Not running" fi ;; restart) $0 stop if is_running; then echo "Unable to stop, will not attempt to start" exit 1 fi $0 start ;; status) if is_running; then echo "Running" else echo "Stopped" exit 1 fi ;; *) echo "Usage: $0 {start|stop|restart|status}" exit 1 ;; esac exit 0
-
将修改后的脚本复制到 `/etc/init.d
创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考