zaki work log

作業ログやら生活ログやらなんやら

[Linux / systemd] OS起動時に1回だけコマンド実行する

systemdを使ってOS起動時にコマンドをワンショット実行するには、Type=oneshotを指定し、ExecStartに実行したいコマンドを指定すればだいたいOK

基本形

[Unit]
Description=my one shot service sample
After=network.target

[Service]
Type=oneshot
ExecStart=/path/to/command

[Install]
WantedBy=multi-user.target

これを /usr/local/lib/systemd/system/my-one-shot-sample.service とかに保存したら、以下コマンドで有効化する。

systemctl enable my-one-shot-sample.service

ユニットファイルを更新した場合

従来通りdaemon-reloadで再読み込みする。

systemctl daemon-reload

複数コマンドを実行したい場合

ExecStartを複数記述すれば、上から順に実行される。

ExecStart=/path/to/command1
ExecStart=/path/to/command2
ExecStart=/path/to/command3

この場合は並列での処理ではなく、1つの処理完了後に次のコマンドが起動する。
また、遅延起動したい場合はtimerを使う方法などもあるが、ExecStartの1コマンド目にsleepを入れれば簡単に実現できる。

シェルではないので;などで並べて書くことはできないので注意。

任意のタイミングで即時起動したい場合

通常のサービス起動の要領でsystemctl startすればそのタイミングで起動する。

sudo systemctl start my-one-shot-sample.service

言及してないその他の記述について

以下で軽く説明してるので参照

zaki-hmkc.hatenablog.com