Assume that there are three files in a directory of my Ubuntu-Linux. One of them is open in a music player, but two others are not open in any application and are not in use of any Process.
I want to delete those two files. In the other words, I want to detect files that are not used by any process, and then delete them.
I tried this:
rm !(lsof | grep "thePath")
but it failed. There are a problem with lsof
here.
Is there any way?
Your syntax is wildly wrong. In the shell, unlike in many other programming languages, putting a command (as if it were a function call) in parentheses does not produce its result.
Instead, you want something like this:
for f in *; do
fuser -s "$f" || rm "$f"
done
I preferred fuser
over lsof
as it allows you to query an individual file.