Issue
I have a data directory on a Debian box containing multiple sub-directories, when the system has processed the contents of a sub-directory it adds a sub-directory ".processed" into it.
Unfortunately when the data is deleted the ".processed" directories are left behind and i have to delete them by hand, in among the directories still containing data.
Is there any way to delete only sub-directories that contain just a directory ".processed" and no other files or directories?
Solution
You can use this shell script:
#!/bin/bash
find . -type d -print | tac | while read -r file ; do
if [[ "$(ls -A "$file")" = ".processed" ]];
then
rmdir "$file"/".processed"
rmdir "$file"
fi
done
This script loop on all directories given by find . -type d
. If it discovers a directory containing only a directory named .processed
, then it delete the .processed
directory and the directory containing it. Only empty directories are removed, so the script use rmdir
. In general, try to avoid using rm -rf
in script, because it can be dangerous...
If the order of directories to remove place a subdirectory before a directory then the rmdir
will fail. Using rm -rf *
solves the issue but is dangerous. The solution here is to pipe to tac
and reverse the order given by find
.
The script works with white spaces in file names. Thanks to the solution from the Sorpigal answer, named pipe to while, newline terminated.
Answered By - Ortomala Lokni