Have lsof take action if a process has a file open — and, ideally, do so repeatedly

Per the EXAMPLES section in the lsof(8) man page
on manpages.ubuntu.com,
I should be able to run a command/take action if a process has a file open:

To take action only if a process has /u/abe/foo open, use:

lsof /u/abe/foo  echo "still in use"

When I try this syntax (in repeat mode), it doesn’t work:

$ lsof -r /u/abe/foo tput bel
lsof: status error on tput: No such file or directory
lsof: status error on bel: No such file or directory
=======

I reviewed the man page,
but it’s lengthy and I guess I’ve overlooked something.

What am I missing?

Asked By: Bink

||

Even though the manpage lists it, that is not a valid lsof invocation. lsof will consider echo and still in use as names:

lsof /u/abe/foo echo "still in use"

To have a result from lsof and act on it you could use the exit code. In bash:

lsof filename && echo "still in use"

or:

lsof filename || echo "not in use"

If you want this to happen repeatedly you can put the above code in a loop or put lsof in repeat mode and then process its standard output, for example in bash:

lsof -t -r2 filename |
grep --line-buffered -v '=======' |
while read pid
do
    echo Process $pid is using the file
done
Answered By: Eduardo Trápani
Categories: Answers Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.