2

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?

Paladinz
  • 23
  • 2
  • Did you try my last answer? If it convince you, you can accept it by clicking on the check mark beside the answer, you can also, if you want, upvote it, by clicking on the up arrow. – Ortomala Lokni Jan 08 '16 at 15:22
  • I haven't had time to try it yet, it's on my list for Saturday tho, fingers crossed it works :) – Paladinz Jan 09 '16 at 00:01
  • Thank you @OrtomalaLokni thats perfect! Does exactly what's needed.Sorry my upovote doesn't show. – Paladinz Jan 09 '16 at 13:04
  • You need a reputation of 15 to [upvote](http://stackoverflow.com/help/privileges/vote-up). – Ortomala Lokni Jan 09 '16 at 16:20

1 Answers1

0

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.

Community
  • 1
  • 1
Ortomala Lokni
  • 56,620
  • 24
  • 188
  • 240
  • Thanks @Ortomala but that gives line 8: syntax error near unexpected token `done' ' – Paladinz Jan 07 '16 at 21:01
  • I've changed the answer and used a simpler way to read through a list of files. – Ortomala Lokni Jan 07 '16 at 22:59
  • Thank you for the edit @Ortomala, unfortunately that also removes all the ***.processed*** directories from non-empty directories leaving no indication as to which directories have been processed :( – Paladinz Jan 08 '16 at 00:29
  • I've changed the script and now use `tac` in order to remove things in the right order. – Ortomala Lokni Jan 08 '16 at 09:28