systemctlとshellの理解を深める

### 最終ゴール
$ sudo systemctl restart mysqld.service
↑これをshellで実行したい

1.まずシェルを作ります。
hello.sh

#!/bin/bash
while true
do
	echo hello world >> /home/vagrant/dev/test3/hello.log
	sleep 1
done

2.実行権限
$ sudo chmod 0755 hello.sh

3./etc/systemd/systemの下にUnit定義ファイルを作成する
$ sudo vi /etc/systemd/system/hello.service

[Unit]
Description = hello daemon

[Service]
ExecStart = /home/vagrant/dev/test3/hello.sh
Restart = always
Type = simple

[Install]
WantedBy = multi-user.target

L ServiceのExecStartが実行したいコマンド
L Restart=alwaysはサーバが不意に落ちた時に対応

4. Unitがserviceとして認識されたか確認
$ sudo systemctl list-unit-files –type=service | grep hello
hello.service disabled

5. 起動してステータス確認
$ sudo systemctl enable hello
$ sudo systemctl start hello
$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: active (running) since 水 2021-01-20 10:35:02 JST; 14s ago
Main PID: 7220 (hello.sh)
CGroup: /system.slice/hello.service
├─7220 /bin/bash /home/vagrant/dev/test3/hello.sh
└─7235 sleep 1

1月 20 10:35:02 localhost systemd[1]: Started hello daemon.
1月 20 10:35:02 localhost systemd[1]: Starting hello daemon…

$ tail hello.log
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
hello world
$ sudo systemctl stop hello

$ sudo systemctl status hello
● hello.service – hello daemon
Loaded: loaded (/etc/systemd/system/hello.service; enabled; vendor preset: disabled)
Active: inactive (dead) since 水 2021-01-20 10:38:06 JST; 21s ago
Process: 7220 ExecStart=/home/vagrant/dev/test3/hello.sh (code=killed, signal=TERM)
Main PID: 7220 (code=killed, signal=TERM)

1月 20 10:35:02 localhost systemd[1]: Started hello daemon.
1月 20 10:35:02 localhost systemd[1]: Starting hello daemon…
1月 20 10:38:06 localhost systemd[1]: Stopping hello daemon…
1月 20 10:38:06 localhost systemd[1]: Stopped hello daemon.

systemctl コマンドは、”systemd” をコントロールするコマンド
なるほど、systemctl restart mysqld.serviceは、mysqldのdaemonを管理してるってことね。
やっと理解した。