Resume bash script after reboot
Quick technique you can use to resume bash script after system reboot.
By Subash Adhikari · · 1 min read
Written in 2017. Commands, prices, and links in this piece may be out of date.
I often write bash scripts to automate common tasks in my projects. Sometimes the script makes changes that need a reboot, and once the machine comes back up the script has to resume from where it left off.
The script below creates a temporary file that acts as a flag, so the script can tell whether it's resuming after a reboot. It also temporarily adds a line to .bashrc or .zshrc so the script runs automatically after the reboot. When the script resumes, it removes the temporary file and the extra line from bashrc or zshrc.
# filename: reload_bash_shell.sh
# check if the reboot flag file exists.
# We created this file before rebooting.
if [ ! -f /var/run/resume-after-reboot ]; then
echo "running script for the first time.."
# run your scripts here
# Preparation for reboot
script="bash /reload_bash_shell.sh"
# add this script to zsh so it gets triggered immediately after reboot
# change it to .bashrc if using bash shell
echo "$script" >> ~/.zshrc
# create a flag file to check if we are resuming from reboot.
sudo touch /var/run/resume-after-reboot
echo "rebooting.."
# reboot here
else
echo "resuming script after reboot.."
# Remove the line that we added in zshrc
sed -i '/bash/d' ~/.zshrc
# remove the temporary file that we created to check for reboot
sudo rm -f /var/run/resume-after-reboot
# continue with rest of the script
fiRelated posts
Thanks for reading. You can also follow along on X or with RSS.