LazerSharks
LazerSharks

Reputation: 3155

Comparing files in two different directories

In the bash script below, I am trying to compare the files of two folders. A file in folder f1 will be deleted if it exists in folder f2.

#!bin/bash

for i in  `dir f1/*`
do
     for j in `dir f2/*`
     do
          if [[ $i = $j ]]
          then
                   `rm -fr f1/$i`
          else
          fi
    done
done

Ive also tried:

#!bin/bash

for i in  f1/*
do
     for j in f2/*
     do
          if [[ $i = $j ]]
          then
                   rm -fr f1/$i
          else
          fi
    done
done

But both give me syntax error near unexpected token 'fi'.

Am I right in my use/lack of backticks or brackets?

Upvotes: 1

Views: 104

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 81052

This script loops over the contents of f2 once for each file in f1(which is going to be quite inefficient for large f1 directories).

You can almost certainly do this in a much simpler fashion using something like rsync or simply a glob to rm.

That being said there's also no reason to test for filename equivalence at all (and especially so when using rm -f). You don't need to test for filename equivalence if all you want to do is access a file by name since you already know the name you care about from your outer loop. Additionally, you don't even need an existence test if you are removing a file with rm -f because rm -f does not fail, even when given a file that does not exist.

That being said there's no reason to loop over f1 at all. Just loop over f2 and delete (with rm -f, no need for -r unless you expect to delete directories) any files that have the same basename in f1 as were in f2:

for file in f2/*; do
    rm -f f1/"$(basename "$file")"
done

Upvotes: 3

Related Questions