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

Do the work

echo “I am now going to back myself up :)!”
sleep 2
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

if [ -f ~/ ]
echo the file exists
sleep 2
echo the file does not exist
sleep 2

Basically, if is there, this script,, runs, which when finished, renames itself. If is not there, the script just finishes. Subsequent runs of the script 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 *