Objective
a problem has been encountered at work today, if you copy the files from directory A to directory B (without the file in directory B) and keep the files in directory A. The focus of the project is as follows:
You need to keep the structure of the file in directory A in directory B. Suppose a directory file A/test/1.txt, transfer to directory B should be b/test/1.txt. You also need to consider whether there is a test directory in directory B, and the multi-level directory should consider recursion. (Fortunately, it's easy to write a directory recursive traversal in the Bash shell.) )
You need to consider whether a file in B already has a file with the same name, and if it exists, you do not need a copy.
Sample project requirements are shown below:
Realize
the project needs to have, know the design to recursion, the code is very good to write. Here is a demo sample for your reference.
#!/bin/bash
function Recursive_copy_file ()
{
dirlist=$ (ls $) for
name in ${dirlist[*]}
do If [f $1/$name]; Then
# If it is a file and the file does not exist, direct copy
if [!-f $2/$name];
then CP $1/$name $2/$name
fi
elif [-D $1/$nam E]; Then
# if it is a directory, and the catalog does not exist, create a directory if
[!-d $2/$name]; then
mkdir-p $2/$name
fi
# recursive copy
Recursive_copy_file $1/$name $2/$name
fi
done
}
source_dir= "/tmp/test/system"
dest_dir= "/tmp/test/systemback"
recursive_copy_file $source _dir $dest _dir