How to run a command before/after package install/removal on Debian/Ubuntu

Create a file inside /etc/apt/apt.conf.d. The following options allow you to run commands or scripts before or after invoking dpkg/apt/apt-get tools:

sh
# This is a list of shell commands to run after invoking dpkg/apt-get # DPkg::Post-Invoke {"command";}; DPkg::Post-Invoke {"/path/to/script";}; # This is a list of shell commands to run before invoking dpkg/apt-get # DPkg::Pre-Invoke {"/path/to/sbin/command";}; DPkg::Pre-Invoke {"/path/to/script";};

(source)