Big Sur - detect when Finder window has closed

I figured out how to solve this.

I repeatedly run the following command in my shell script in a loop, with a short sleep between loop iterations:

/usr/bin/osascript -e 'tell application "Finder" to get the name of every window' | grep '/path/to/directory'

As soon as it stops finding a match, I break out of the loop, since it means that the Finder window for /path/to/directory has closed.