周凯,个人博客

  • 前端
  • 嵌入式
  • 工具
  • 后端
  • 随笔
个人记录
  1. 首页
  2. linux
  3. 正文

linux 注册服务,开机启动指定脚本

2023年 3月 20日 468点热度 0人点赞 0条评论
  • 创建 svc.sh文件
  • 赋予权限 chmod +x ./svc.sh
  • 如果需要延迟执行,修改Service

    ExecStartPre=/bin/sleep 6  # 延迟6秒执行
#!/bin/bash
# 需要启动脚本的位置
SCRIPT_PATH="/data/app/ai-qa/java.sh"
# 服务名称
SERVICE_NAME="ai-qa"

# 添加到开机启动
add_to_startup() {
    if [ ! -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
        echo "[Unit]
Description=My Startup Service

[Service]
ExecStartPre=/bin/sleep 6
ExecStart=$SCRIPT_PATH
Restart=always

[Install]
WantedBy=multi-user.target" | sudo tee /etc/systemd/system/$SERVICE_NAME.service

        echo "服务已添加到开机启动"
    else
        echo "服务已存在,无需重复添加"
    fi

    sudo systemctl enable $SERVICE_NAME
}

# 移除开机启动
remove_from_startup() {
    if [ -f "/etc/systemd/system/$SERVICE_NAME.service" ]; then
        sudo systemctl disable $SERVICE_NAME
        sudo rm /etc/systemd/system/$SERVICE_NAME.service
        echo "服务已从开机启动中移除"
    else
        echo "服务不存在,无需移除"
    fi
}

# 启动服务
start_service() {
    echo "将在 30 秒后启动服务: $SERVICE_NAME"
    sleep 30
    sudo systemctl start $SERVICE_NAME
    echo "服务已启动: $SERVICE_NAME"
}

# 停止服务
stop_service() {
    sudo systemctl stop $SERVICE_NAME
    echo "服务已停止: $SERVICE_NAME"
}

# 主程序
case $1 in
    add)
        add_to_startup
        ;;
    remove)
        remove_from_startup
        ;;
    start)
        start_service
        ;;
    stop)
        stop_service
        ;;
    *)
        echo "用法: $0 {add|remove|start|stop}"
        exit 1
        ;;
esac

🎯 拓展阅读提示

本文涉及的内容已同步至公众号后台,我会在那里分享更多深度内容和实用技巧

→ 点击关注:一行梦境

公众号二维码
本作品采用 知识共享署名 4.0 国际许可协议 进行许可
标签: 暂无
最后更新:2024年 10月 13日

周凯

这个人很懒,什么都没留下

打赏 点赞
下一篇 >

文章评论

razz evil exclaim smile redface biggrin eek confused idea lol mad twisted rolleyes wink cool arrow neutral cry mrgreen drooling persevering
取消回复

COPYRIGHT © 2022-现在 周凯,个人博客. ALL RIGHTS RESERVED.

Theme Kratos Made By Seaton Jiang

蒙ICP备18004897号