𝖄𝕺🌎𝕿𝕽𝕺¥

𝖄𝕺🌎𝕿𝕽𝕺¥

𝕴 𝖉𝖔 𝖒𝖆𝖌𝖎𝖈
github

Linux如何設置開啟啟動命令

示例#

假設我想要在我的 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
載入中......
此文章數據所有權由區塊鏈加密技術和智能合約保障僅歸創作者所有。