RPM SPEC pre/post/preun/postun argument values

More as a reminder for myself, but hope it helps you.

RPM has 4 parts where (shell) scripts can be used:

  • %pre - Executed before installation.
  • %preun - Executed before un-installation.
  • %post - Executed after installation.
  • %postun - Executed after un-installation.

In all these parts or sections the variable "$1" can be checked to see what's being done:

  • Initial installation
  • Upgrade
  • Un-installation

This table show the values of "$1" per section related to the action.

%pre %preun %post %postun
Initial installation 1 not applicable 1 not applicable
Upgrade 2 1 2 1
Un-installation not applicable 0 not applicable 0

This can be used for example when registering new services:

case "$1" in
    # This is an initial install.
    chkconfig --add newservice
    # This is an upgrade.
    # First delete the registered service.
    chkconfig --del newservice
    # Then add the registered service. In case run levels changed in the init script, the service will be correctly re-added.
    chkconfig --add newservice

case "$1" in
    # This is an un-installation.
    service newservice stop
    chkconfig --del newservice
    # This is an upgrade.
    # Do nothing.

Good to know; this is the order for certain RPM actions:

install upgrade un-install
%pre ($1=1) %pre ($1=2) %preun ($1=0)
copy files copy files remove files
%post ($1=1) %post ($1=2) %postun ($1=0)
%preun ($1=1) from old RPM.
delete files only found in old package
%postun ($1=1) from old RPM.

So when upgrading the exemplary package "software" from version 1 to version 2, this is the script (%post and %postun) order:

  1. Run %pre from "software-2".
  2. Place files from "software-2".
  3. Run %post from "software-2".
  4. Run %preun from "software-1".
  5. Delete files unique to "software-1".
  6. Run %postun from "software-1".

This means there are cases where "software-1" has incorrect scripts, and there is no way to upgrade. In that case the RPM can be uninstalled, which might execute different commands because $1 equals 0 (un-install) instead of 1 (upgrade).
When the RPM uninstall scripts fail, the only way to fix things is to manually execute the intended commands... RPM is not perfect, but it's pretty well thought through!