示例#
假設我想要在我的 Linux 設備啟動時自動執行兩個指令:
cd /test
nohup python3 -m http.server 6666
❗提示:為什麼要使用 nohup?因為 nohup 是一個靜音指令,不會將指令輸出到終端,運行日誌將保存在 /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 文件#
在 /etc/systemd/system
目錄中創建一個名為 test.service
的文件,輸入:
[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