Worth knowing that most CI systems have built-in path filters, and for the common case they are better than any script.
A rule saying this job only runs when files under a given path changed is evaluated by the platform, handles the branch and merge cases itself, and cannot drift out of sync with your diffing logic.
Use the script only for what the filters cannot express — passing the actual file list to a tool, or fanning out over changed directories.
For a repository with several packages, the further step is a build tool that understands the dependency graph. Path filters know that a file changed; a build graph knows that changing it means three packages need rebuilding and the other twelve do not. That distinction is where the real time is saved, and no amount of diffing gets you there.