Bash Shell recursively implements file copy in directory

Source: Internet
Author: User
Tags file copy
PrefaceThere is a problem with working today, if you copy the file in directory A to directory B (without the file in directory B), and keep the file structure 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:

ImplementProject requirements have, know the design to recursion, the code is very good to write. Here is a demo example for everyone to refer to.
#!/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, 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

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.