LoginSignup
0
2

More than 1 year has passed since last update.

【bashスクリプト実装】OSを安全にシャットダウンするスクリプト

Last updated at Posted at 2022-09-11

背景

SQLのトランザクション処理、アプリケーション処理中に、
うっかりシャットダウンしたり再起動したりしてしまうことってあるかと思います。
ミドルウェアが強制停止すると次回起動時にデータ不整合が出るので、
誤って停止しないようにする必要が出てきます。
このため、プロセス確認をしてからシャットダウンするようなスクリプトがあると便利です。

実施内容

プロセス確認をしてからシャットダウンするようなスクリプトを作成しました。

  • 暫定でループ回数を1000回
  • 問題なければシャットダウンする

という作りとなっているので、必要であればカスタマイズするのもありかと思います。

OS停止スクリプト

[root@homeserver ~]# cat os_safetyshutdown.sh
#!/bin/bash
res=1
dup=0
while true
do
   statusNumber=`ps -ef | grep sh | egrep -v 'grep|kworker|kdmflush|sshd|os_safetyshutdown|pts|-bash|emerg_metabase_reload|online' | wc -l`
   if [ ${statusNumber} = 0 ]; then
      #res=0
      dup=$(($dup+1))
      echo $dup
      if [ ${dup} = 1000 ]; then
         res=0
         break
      fi
   fi
   #sleep 1
done
if [ ${res} = 0 ]; then
   shutdown -h now
fi
[root@homeserver ~]#

OS再起動スクリプト


[root@homeserver ~]# cat os_safetyreboot.sh
#!/bin/bash
res=1
dup=0
while true
do
   statusNumber=`ps -ef | grep sh | egrep -v 'grep|kworker|kdmflush|sshd|os_safetyshutdown|pts|emerg_metabase_reload|online' | wc -l`
   if [ ${statusNumber} = 0 ]; then
      #res=0
      dup=$(($dup+1))
      echo $dup
      if [ ${dup} = 1000 ]; then
         res=0
         break
      fi
   fi
   #sleep 1
done
if [ ${res} = 0 ]; then
   shutdown -r now
fi
[root@homeserver ~]#
0
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
2