#!/bin/bash # 确保脚本以root权限运行 if [ "$EUID" -ne 0 ]; then echo "请使用root权限运行此脚本" exit 1 fi SERVICE_NAME="weight-reader" INSTALL_DIR="/opt/weight-reader" SERVICE_FILE="/etc/systemd/system/weight-reader.service" # 创建安装目录 create_install_dir() { echo "创建安装目录..." mkdir -p "$INSTALL_DIR" chmod 755 "$INSTALL_DIR" } # 复制文件 copy_files() { echo "复制文件..." cp weight_reader "$INSTALL_DIR/" cp config.json "$INSTALL_DIR/" cp weight-reader.service "$SERVICE_FILE" chmod 755 "$INSTALL_DIR/weight_reader" chmod 644 "$INSTALL_DIR/config.json" chmod 644 "$SERVICE_FILE" } # 安装服务 install_service() { echo "安装服务..." systemctl daemon-reload systemctl enable $SERVICE_NAME systemctl start $SERVICE_NAME echo "服务已安装并启动" } # 卸载服务 uninstall_service() { echo "停止并卸载服务..." systemctl stop $SERVICE_NAME systemctl disable $SERVICE_NAME rm -f "$SERVICE_FILE" rm -rf "$INSTALL_DIR" systemctl daemon-reload echo "服务已卸载" } # 启动服务 start_service() { echo "启动服务..." systemctl start $SERVICE_NAME echo "服务已启动" } # 停止服务 stop_service() { echo "停止服务..." systemctl stop $SERVICE_NAME echo "服务已停止" } # 重启服务 restart_service() { echo "重启服务..." systemctl restart $SERVICE_NAME echo "服务已重启" } # 查看服务状态 status_service() { systemctl status $SERVICE_NAME } # 显示使用帮助 show_help() { echo "使用方法: $0 [命令]" echo "命令:" echo " install - 安装并启动服务" echo " uninstall - 停止并卸载服务" echo " start - 启动服务" echo " stop - 停止服务" echo " restart - 重启服务" echo " status - 查看服务状态" echo " help - 显示此帮助信息" } # 主程序 case "$1" in "install") create_install_dir copy_files install_service ;; "uninstall") uninstall_service ;; "start") start_service ;; "stop") stop_service ;; "restart") restart_service ;; "status") status_service ;; "help"|"") show_help ;; *) echo "未知命令: $1" show_help exit 1 ;; esac exit 0