Search code examples
bashshellrm

bash script to remove files matching those in another directory


I'm trying to create a script that retrieves files (including subfolders) from CVS and stores them into a temporary directory /tmp/projectdir/ (OK), then removes copies of those files from my project directory /home/projectdir/ (not OK) without touching any other files in the project directory or the folder structure itself.

I've been attempting two methods, but I'm running into problems with both. Here's my script so far:

#!/usr/bin/bash

cd /tmp/
echo "removing /tmp/projectdir/"
rm -rf /tmp/projectdir

# CVS login goes here, code redacted
# export files to /tmp/projectdir/dir_1/file_1 etc
cvs export -kv -r $1 projectdir

# method 1
for file in /tmp/projectdir/*
do
  # check for zero-length string
  if [-n "$file"]; then
    echo "removing $file"
    rm /home/projectdir/"$file"
  fi
done

# method 2
find /tmp/projectdir/ -exec rm -i /home/projectdir/{} \;

Neither method works as intended, because I need some way of stripping /tmp/projectdir/ from the filename (to be replaced with /home/projectdir/) and to prevent them from executing rm /home/projectdir/dir_1 (i.e. the directory and not a specific file), but I'm not sure how to achieve this.

(In case anybody is wondering, the zero-length string bit was an attempt to avoid rm'ing the directory, before I realised /tmp/projectdir/ would also be a part of the string)


Solution

  • You can use:

    cd /tmp/projectdir/
    find . -type f -exec rm -i /home/projectdir/{} \;