サンプル#
Linux デバイスの起動時に 2 つのコマンドを自動実行したいとします:
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 ファイル#
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