What's the fastest way using lsof to find a single open file?

こ雲淡風輕ζ 提交于 2019-11-30 20:29:09
R Samuel Klatchko

I found a much better way. With lsof (tested on version 4.63), you can directly query a specific file:

if lsof filename > /dev/null; then
    # file is open
fi

Well, you can skip wc and use the return value of grep (grep returns 0 (i.e. success) if it detects the pattern and 1 (i.e. not-success) if it does not detect the pattern):

if lsof | grep filename > /dev/null; then
    # filename is in output of lsof
fi

You can improve this a bit by using grep's -l flag:

if lsof | grep -l filename > /dev/null; then
...

This tells grep to stop looking once it detects it's first match.

Use fuser. It returns non-zero if any of the files specified are in use, and zero if they're all available.

Don't. The answer might change by the time you try to do anything with the result. Instead, try to do whatever you intended to do with the file and handle the "in use" error or "sharing violation".

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!