[Klug-general] Bash script to delete folders if they exists (revisited)

David Halliday david.halliday at gmail.com
Fri Jul 15 18:05:00 UTC 2011


why not create the list using the find command.

find directories matching pattern: find -type d -name fred*
then pipe the output into grep: grep -v -f myFilesToKeep.txt

Using -v reverses the output so it only outputs lines that aren't in the
list (one per line).

so:
amon at amon1:~$ find / -maxdepth 1 -type d
/
/srv
/sbin
/var
/selinux
/cdrom
/lib32
/media
/home
/sys
/tmp
/mnt
/opt
/dev
/usr
/root
/bin
/boot
/etc
/lost+found
/lib
/proc
amon at amon1:~$ more myFilesToKeep.txt
tmp
sys
amon at amon1:~$ find / -maxdepth 1 -type d | grep -v -f myFilesToKeep.txt
/
/srv
/sbin
/var
/selinux
/cdrom
/lib32
/media
/home
/mnt
/opt
/dev
/usr
/root
/bin
/boot
/etc
/lost+found
/lib
/proc

so:

for MYDIR in `find / -maxdepth 1 -type d | grep -v -f myFilesToKeep.txt`
do
  rm -rf $MYDIR
done

*NOTE: Do not run this as is! unless you want to be left with only /tmp and
/sys on your system!*
*
*
But that's a starting point, play with the man pages for find and grep.

On 15 July 2011 14:22, Nathan Friend <nathan.friend at gmail.com> wrote:

> Afternoon KLUG,
> Last year I wanted a bash script to delete folders if they existed in
> a predefined list file.  The end result was:
>
> while read dir
> do
> if [ -d $dir ]
> then
> rm -R $dir
> echo "Directory $dir found and deleted."
> else
> echo "Directory $dir not found."
> fi
> done < dir_list
>
>
> dir_list file contains
> /Users/user1
> /Users/user2
> /Users/user3
>
> This year I need to delete all files in the /Users/ folder except the ones
> listed in dir_list.
>
> Any ideas?
>
> Cheers,
>
> Nathan.
>
> _______________________________________________
> Kent mailing list
> Kent at mailman.lug.org.uk
> https://mailman.lug.org.uk/mailman/listinfo/kent
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.lug.org.uk/pipermail/kent/attachments/20110715/8509ca44/attachment-0001.htm>


More information about the Kent mailing list