Run Once Only Bash Scripts

I am constantly amazed by what can be achieved with a simple bash script or two. I had a situation where I needed a script to run only once, and to not get any errors spat out at me from the cli. I needed a second script to call the run once script to go into rc.local, a file I didn’t want to mess with, so the call in rc.local would just be a quick file check after the first run. for me, the clever bit is that the scriptI have to do the work can “move” (rename) itself once it has done its business, thereby ensuring it is not called upon again, but is still there if needed.

Here’s the script that does the work (called once.sh):

#!/bin/bash
Do the work

echo “I am now going to back myself up :)!”
sleep 2
mv once.sh once.sh.bak
echo file backed up
sleep 2
exit 0

The key line is the mv command, running on itself! I’ll remove the comments for the production setting

Here’s is the script that calls the one above (called runitonce.sh):

 #!/bin/bash
if [ -f ~/once.sh ]
then
echo the file exists
sleep 2
~/once.sh
else
echo the file does not exist
sleep 2
fi

Basically, if once.sh is there, this script, runitonce.sh, runs once.sh, which when finished, renames itself. If once.sh is not there, the script just finishes. Subsequent runs of the script runitonce.sh called in rc.local just run through as there is no file to run. Simples :)

Leave a Reply

Your email address will not be published. Required fields are marked *