Match and copy the contents of the same directory name to a new directory with the same name?

Viewed 31

My script should check a directory called /etc/scriptbuilder/default/contents which will hold some directories, if a directory in the contents directory matches one in the project directory the files in the contents directory should be copied to the project directory (so, if /etc/scriptbuilder/default/contents/docs and /project/docs both exist, the contents of /etc/scriptbuilder/default/contents/docs should be copied).

I'm having trouble making this work. It has to find a match of the same directory name and copy the contents over from the contents directory to the project directory if they have the same directory name. This is what I have so far:

 #! /bin/bash


  if [ -d "$/etc/scriptbuilder/default/contents ]; then

 if [[ "/etc/scriptbuilder/default/contents" =~ name ]]; then

 cp -a #I'm not sure how to copy and check for the name on the project 
       directory

 fi
 fi
2 Answers

Something like that finds the the directories you are looking for and prints them.

source="/etc/scriptbuilder/default/contents"
destination="/home/something/project"

# loop the directories of the source folder
cd "$source"
for name in */ ; do

    # create the source and the possible destination directory paths
    s="$source/$name"
    d="$destination/$name"

    # check if the directory exists in the project
    if [ -d "$d" ]; then

        echo "TODO: Perfrom copy of from $s to $d"
    fi
done

If you need help with copy command also post a comment.

With loop it could be like this:

Dir1=path_to_contents/contents
Dir2=path_to_project/project

for i in $(find "$Dir1/" "$Dir2/" -printf '%P\n' | sort | uniq -d)
do
  cp -r $Dir1/$i $Dir2
done
Related