Preface to the work today encountered a problem, if you copy the file in directory A to directory B (premise directory B does not have the file), and maintain the structure of the file in directory A. The project focuses on the following:
- You need to keep the structure of the file in directory A in directory B. Suppose that 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 multilevel directory should consider recursion. (Fortunately, it's easier to write a recursive traversal of a directory in the Bash shell.) )
- You need to consider whether the file in a has a file with the same name in B, and if it does, it does not need to be copied.
The project requirements sample diagram is as follows:
The implementation of the project requirements, know that the design to recursion, the code is very good to write. Here is a demo example for everyone to refer to.
#!/bin/bashfunction 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, copy the if [!-f $2/$name], then CP $1/$name $2/$name fi elif [-D $1/$name ]; then # If it is a directory, and the directory 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
Bash Shell recursively implements file copy in directory