I want to create a script that will run only on first boot, and never again. I am working on a VM that will be converted on a template so I want to make sure I can create a script that can run automatically when the server boots.

I have some clues that I can put a script under /etc/init.d/firstboot for example, and use chkconfig to do it on rhel (which seems not available on Ubuntu), but I need to do it on Ubuntu 14 and 16, any ideas? -- can I assume that if I put a script under /etc/init.d it will run at boot?

I've been googling but I see many different things. For example I saw something similar for rhel:

# chkconfig: 2345 9 20
# description: long description

case "$1" in
    Do your thing !!!
    chkconfig yourscript off
    # do nothing

any help is much appreciated


You could start your script with systemd. Write a systemd unit like:




After enabling this unit it should only start if the file in ConditionPathExists exists. You could write your script to remove that file after running. Check systemd.unit there are more such checks, for example ConditionFileNotEmpty or ConditionDirectoryNotEmpty which can also be handy.

  • but this would not work on Ubuntu 14 right? can I write then a script that deletes itself and put it at the end of /etc/rc.local ? would this work for both 14 and 16? – user3311890 Jun 1 '17 at 13:03
  • Well, I would not write a script which deletes itself, seems hack-ish and tricky to evaluate. You could do it the same way: let the script create a file and check the presence of that file before executing. systemd seems fully supported on Ubuntu 15.04 but available on older versions. Before systemd Ubuntu used upstart. Look into the upstart documentation on how to run a script there. – duenni Jun 1 '17 at 13:13
  • That's why chmod -x $0 is the best solution that I suggested. – Marco Jun 2 '17 at 12:30
  • @Marco I did not say otherwise and was not the one who downvoted you. I just provided another solution (with systemd). – duenni Jun 2 '17 at 13:00
  • @duenni: LOL, np mate! :) – Marco Jun 2 '17 at 13:01

It won't run at boot just because it's in /etc/init.d/.

The script can be in /etc/init.d, but you will have to initctl reload-configuration or you may put the script where you want and echo "/path/to/yourscript start &" >> /etc/rc.local.

Then, just add chmod -x $0 at the end of the start section and it will never execute again.

Or if you prefer the script to be deleted instead, use rm $0. If you opted for initctl way, use rm $0 && initctl reload-configuration to disable instead.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.