RafaelGP
RafaelGP

Reputation: 1889

bash - For every file in a directory, copy it into another directory, only if it doesn't exists there already

Thank you very much in advance for helping!

I have a directory with some html files

$ ls template/content/html
devel.html
idex.html
devel_iphone.html
devel_ipad.html

I'd like to write a bash function to copy every file in that folder into a new location (introduction/files/), ONLY if a file with the same name doesn't exist already there.

This is what I have so far:

orig_html="template/content/html";
dest_html="introduction/files/";

function add_html {
    for f in $orig_html"/*";
    do
        if [ ! -f SAME_FILE_IN_$dest_html_DIRECTORY ];
        then
            cp $f $dest_html;
        fi
    done
}

The capital letters is where I was stuck.

Thank you very much.

Upvotes: 0

Views: 648

Answers (4)

Bruno von Paris
Bruno von Paris

Reputation: 902

Your $f variable contains the full path, because of the /*. Try doing something like:

for ff in $orig_html/*
  do
    thisFile=${ff##*/}
    if [ ! -f ${dest_html}/$thisFile ]; then
       cp $ff ${dest_html}
    fi
  done

Upvotes: 0

turtledove
turtledove

Reputation: 25904

use rsync like this:

rsync -c -avz --delete $orig_html $dest_html

which keep $orig_html indentical with $dest_html based file checksum.

Upvotes: 2

Miquel
Miquel

Reputation: 15675

Would the -n option be enough for your needs?

   -n, --no-clobber
          do not overwrite an existing file (overrides a previous -i option)

Upvotes: 4

Brian Agnew
Brian Agnew

Reputation: 272257

Do you need a bash script ? cp supports the -r (recursive) option, and the -u (update) option. From the man page:

   -u, --update
      copy only when the SOURCE file is  newer  than  the  destination
      file or when the destination file is missing

Upvotes: 0

Related Questions