示例#
假设我想让我的 Linux 设备启动时自启动两条指令:
cd /test
nohup python3 -m http.server 6666
❗tips: 为什么用 nohup,因为 nohup 是静默指令不会输出指令到终端,运行 log 会储存在 /test/nohup.out 文件中
实操#
.sh 文件#
创建一个名为 test.sh 文件,输入以下合并代码
#!/bin/bash
(cd /test && nohup python3 -m http.server 6666) &
此处使用 && 运算符来确保只有在 cd 命令成功执行后才执行 nohup 命令。& 符号用于在后台运行 nohup python3 -m http.server 6666 命令。
.service 文件#
创建名为 test.service 的文件在 /etc/systemd/system 目录中,键入:
[Unit]
Description=HTTP Server
[Service]
ExecStart=/test/test.sh
Restart=always
[Install]
WantedBy=default.target
使用以下命令启用服务并启动它:
sudo systemctl enable test.service
sudo systemctl start test.service
完成,nohup python3 -m http.server 6666 命令将在 Linux 启动时自动执行。
停止服务:
sudo systemctl stop http_server.service
禁用服务:
sudo systemctl disable http_server.service