Execute command before shutdown/reboot [duplicate]

To execute a script at shutdown or reboot:

  1. save your script in /etc/rc6.d
  2. Make it executable: sudo chmod +x K99_script

Notes:

  • The script in rc6.d must be with no .sh extension
  • The name of your script must begin with K99 to run at the right time.
  • The scripts in this directory are executed in alphabetical order.

source


  1. Create a shell executable file with your script in /etc/init.d/ directory.

  2. Since this has to be executed during shutdown or reboot need to create softlinks in /etc/rc0.d/ and /etc/rc6.d

Example:

sudo ln -s /etc/init.d/<your_file> /etc/rc0.d/k99stop_vm
sudo ln -s /etc/init.d/<your_file> /etc/rc6.d/k99stop_vm
sudo chmod a+x /etc/init.d/<your_file>

If your vagrant VMs are using VirtualBox, you can modify /etc/default/virtualbox and change the line that reads:

SHUTDOWN_USERS=""

to

SHUTDOWN_USERS="all"

That fixed it for me on Ubuntu 14.04.