Bash – Run a Script Once on Reboot

bashcentoscronrebootshell

CentOS9

Keeping in mind this question: https://serverfault.com/questions/1099284/centos-how-to-keep-previous-service-state-on-reboot

It seems that it is not possible to achieve what I need. Is that correct?

What I need – to run a script which stops a service, collects and zips logs, then updates OS and reboots (in case there were kernel updates). My problem is that after the reboot the service starts again. It is undesirable.

One way to solve it would be to somehow make CentOS to run a script on this particular reboot, NOT any reboot. So this script can only be run after reboot from the script described above. The scripts stops the service again..

Is there a way to do so?

Best Answer

You can use a "flag" file and an @reboot cron job:

#!/bin/bash
# flag file must exist across reboots 
flag="/tmp/myflagfile"
#
# if there is no $flag, this is the 1st time
if [[ ! -f "$flag" ]] ; then
  touch "$flag"
  do_firsttime
else
  rm "$flag"
  do_secondtime
fi

You can control behavior by creating (or not) the $flag file.

Related Question