jmweathers
jmweathers

Reputation: 11

Checkin if a Variable File is in another directory

I'm looking to check if a variable file is in another directory, and if it is, stop the script from running any farther. So far I have this:

#! /bin/bash 
for file in /directory/of/variable/file/*.cp;
do
test -f /directory/to/be/checked/$file;
echo $?
done

I ran an echo of $file and see that it includes the full path, which would explain why my test doesn't see the file, but I am at a loss for how to move forward so that I can check.

Any help would be greatly appreciated!

Thanks

Upvotes: 1

Views: 38

Answers (2)

shellter
shellter

Reputation: 37298

I think you want

#! /bin/bash 
for file in /directory/of/variable/file/*.cp  ; do
   newFile="${file##*/}"
   if test -f /directory/to/be/checked/"$newFile" ; then
      echo "/directory/to/be/checked/$newFile already exists, updating ..."
   else
      echo "/directory/to/be/checked/$newFile not found, copying ..."
   fi
   cp -i "$file" /directory/to/be/checked/"$newFile"
done

Note that you can replace cp -i with mv -i and move the file, leaving no file left behind in /directory/of/variable/file/.

The -i option means interrogate (I think), meaning if the file is already there, it will ask you overwrite /directory/to/be/checked/"$newFile" (or similar) to which you must reply y. This will only happen if the file already exists in the new location.

IHTH

Upvotes: 1

Daniel Abercrombie
Daniel Abercrombie

Reputation: 381

The command basename will give you just the file (or directory) without the rest of the path.

#! /bin/bash 
for file in /directory/of/variable/file/*.cp;
do
    test -f /directory/to/be/checked/$(basename $file);
    echo $?
done

Upvotes: 0

Related Questions