find and remove all closed files that are not modified in some-time

842 views Asked by At

I'm building a script in linux that will remove files from the disc that aren't in used currently by the OS. I want to use find command so I can execute rm for all the files that I find that are not open. I tried so far this command without success:

find /folderToSearch/ -type f | while read filename ; do /sbin/fuser -s $filename || echo $filename ; done

I found this command in some website it supposed to print all files that are not in used. Although when I open using 'vi' command concurrently to find it still printing the filename.

1

There are 1 answers

5
Sriharsha Kalluru On BEST ANSWER

To get the list of open files you can use lsof command. Get all the list of files from find command in a directory and remove them all.

1). Get the list of open files in a directory.

lsof /folderToSearch |awk '{print $NF}'|sed -e '1 d' |sort |uniq >/tmp/lsof

2). Get the list of files in a directory.

find /folderToSearch -type f -print >/tmp/find

3). Remove the /tmp/lsof list from /tmp/find file and then remove them.

grep -v  -w -f /tmp/lsof /tmp/find |xargs rm -f