Run script before every Time Machine backup? I would like to be able to run a bash script just before Time Machine runs, every time
This script generates some content to be written on a file which needs to be backed up by TM.

I have looked around, but surprisingly no one seemed to have asked this before. Any idea?
That's not possible as far as I know. There aren't any real “hooks” into Time Machine.

However, you can do something nearly as good: you can disable the automatic backups that Time Machine does and run it manually instead:

#!/bin/sh

run_your_command_here

run_another_command_here

and_so_on

tmutil startbackup --block --auto

exit 0


Note this bit from man tmutil


  The --auto option provides a supported mechanism with which to
  trigger "automatic-like" backups, similar to automatic backups
  that are scheduled by the system. While this is not identical
  to true system-scheduled backups, it provides custom schedulers
  the ability to achieve some (but not all) behavior normally
  exhibited when operating in automatic mode.


It is not clear to me what the difference is, but it's worth noting that one exists.