Skip to content
Advertisement

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

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.

Advertisement

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
Advertisement