Wait until a command opened a file

In my last post I wrote:

The sleep 0.3s is needed because xdg-open exits right after starting the program, and when invoked by mutt it means that mutt could delete the attachment before evince has a chance to open it. I had to use the same workaround for sensible-browser, since the same happens when a browser opens a document in an existing tab. I feel like writing some wrapper about all this that forks the viewer, then waits for an IN_OPEN event on its argument via inotify before exiting.

I wrote it: https://github.com/spanezz/waitused/

$ ./waitused --help
usage: waitused [-h] path ...

Run a command exiting only after it quits and a given file has been opened and
closed

positional arguments:
  path        file to monitor
  command     command to run

optional arguments:
  -h, --help  show this help message and exit

This works around situations like mutt deleting the temporary attachment file after run-mailcap is run, while run-mailcap runs a program that backgrounds before opening its input file.

Example

waitused file.pdf xdg-open file.pdf
waitused file.pdf run-mailcap file.pdf

Example ~/.mailcap entry

application/pdf; waitused -- %s xdg-open %s; test=test -n "$DISPLAY"

Update: Teddy Hogeborn pointed out that the initial mailcap entry would fail on files starting with a dash. I added -- for waitused, but unfortunately there seems to be no way at the moment to have xdg-open open files starting with a dash (see: #964949