Implement a recursive copy of a file in a directory using the bash Shell _linux Shell

Source: Internet
Author: User

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 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.