Wednesday, February 11, 2009

Quick Perl for Bash Boolean Woes

My task is simple; delete files that are in one data center's SAN but not in any of the others. Though, to be sure that the files really do not exist in the other data centers, I want to do a little logic to only delete the file if they do not exist in any of the data centers.

So, maybe my brain isn't working properly or I just knew that perl would've been quicker, but I couldn't find the right way to use the -a (AND) bash boolean operator. If anyone knows how I could use bash's booleans to test if a file does not exist in location a, b, c, ..., n+1, then I would be more than curious to know!

This did NOT work: if [ ! -f $x -a ! -f $y -a ! -f $z ] ; then ...

I ended up doing the following in perl fyi:


#!/usr/bin/perl -w

open(FILE, "files_to_del.txt") || die("Could NOT open!");
@cfdata=;
close(FILE);

$ny1="/mnt/ny1/www/";
$ny2="/mnt/ny2/www/";
$sj1="/mnt/sj1/www/";
$tx1="/mnt/tx1/www/";

$count=0;
foreach $filepath (@cfdata) {
chomp($filepath);
$ny1file=$ny1 . $filepath;
$ny2file=$ny2 . $filepath;
$sj1file=$sj1 . $filepath;
$tx1file=$tx1 . $filepath;
if (! -e $ny1file && ! -e $sj1file && ! -e $tx1file) {
$count++;
print "DELETING: $count $ny2file\n";
unlink($ny2file);
}
}


Cheers!

2 comments:

Unknown said...

A late response here. Just in case you're still interested, here is a way to do this in Bash:

if [ ! -f dir1/file ] && [ ! -f dir2/file ] ...

Instead of building up those path individually, I would probably do something like this instead:

DIRS="dir1 dir2 dir3"
for dir in $DIRS; do
    if [ -f $dir/$file ]; then
        found_it=true
        break
    fi
done

if ! ${found_it:-false}; then
  ...
fi

Unknown said...

aha! well now i can try one of these methods out the next time i have a similar need to do so. thank you kindly. :)

cheers!