In Bash, there's an easy way to check for this. When called without any arguments, the lsof program shows a list of all open files on the system. You can also call it with the full path of the filename that you are checking, and it will show only the processes that have that file open. For example, we can look at /dev/null, which seems to pretty much always be open on my system:
$ lsof /dev/null
COMMAND PID USER FD TYPE DEVICE SIZE NODE NAME
gconfd-2 6668 jhall 0u CHR 1,3 6663 /dev/null
gconfd-2 6668 jhall 1u CHR 1,3 6663 /dev/null
gconfd-2 6668 jhall 2u CHR 1,3 6663 /dev/null
...snip...
The lsof program also has an exit status of 0 if it returns any information, and an exit status of 1 if it did not. Since we're only interested in that error status and not in any of the information returned, we can throw it away by redirecting STDOUT and STDERR to /dev/null with &>:
$ lsof /dev/null &> /dev/null && echo "The file is open" || echo "The file is not open"
The file is open
Breaking this down a little further, if "lsof /dev/null &> /dev/null" was successful (returned an error status of 0), then it will run the first echo command. If not, that will make both the lsof command and the first echo command unsuccessful (error status of 1 for both) and the echo command after the pipes will run.
If it's a little confusing having "/dev/null" in that command twice, try running it on a file that's likely to not be open, like /proc/cpuinfo:
$ lsof /proc/cpuinfo &> /dev/null && echo "The file is open" || echo "The file is not open"
The file is not open
Just a handy little bit of Bash Fu to brighten your day.
No comments:
Post a Comment
Comments for posts over 14 days are moderated
Note: Only a member of this blog may post a comment.