Shell script implementation recursively copies files from a folder _linux shell

Source: Internet
Author: User

Demand

I wrote this script two days ago when I met the need to extract a file in a 10-story folder.

A file structure like the following:

Copy Code code as follows:

Dir1
├──a
│├──b
││└──file1
│└──file2
├──c
│└──d
│├──e
││└──file4
│└──file3
└──file5

We need to extract the file1~file5 and put it in another folder.

Script

The script getfilefromdir.sh as follows:

Copy Code code as follows:

#!/bin/bash
#desc: Get file from directory
#example: sh getfilefromdir.sh A B

init_path=${1%/}
save_path=${2%/}

function Checksavepath () {
If [-D $SAVE _path]
Then
RM-RF $SAVE _path
Fi

mkdir ${save_path}
Touch $SAVE _path ". Log"
}

function Getfilefromdir () {
For file in ' ls $ '
Todo
If [-D $/$file]
Then
Getfilefromdir "/" $file
Else
Local path= "$1/$file"
Local name= $file
if [!-F $SAVE _path "/" $name]
Then
echo "CP ${path} to ${save_path}/${name}"
CP ${path} "${save_path}/${name}"
Else
echo "${path} file already exists"
echo "${path}" >> $SAVE _path ". Log" 2>&1
Fi
Fi
Done
}

Checksavepath

For Sfol in ${init_path}
Todo
Getfilefromdir ${sfol}
Done

Run

Copy Code code as follows:

SH getfilefromdir.sh dir1/dir2

The first parameter is the source folder, and the second is the target folder (no need to create in advance).

If there is a file with the same name, there will be a dir2.log

The results are:

Copy Code code as follows:

Dir2
├──file1
├──file2
├──file3
├──file4
└──file5

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.