Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copying directories recursively using shell script

Tags:

shell

Should be an easy question for the gurus here, though it's hard to explain it in text so hopefully this is clear. I've got two directories on a box with some flavor of unix on it. I've got a script that I want to use to move all the files and directories from one location to another.

First, an example of how the directories look:

Directory A: final/results/2012/2012-02/2012-02-25/name/files

Directory B: test/results/2012/2012-02/2012-02-24/name/files

So you see they're very similar. What I want to do is move everything from the Directory B 2012 directory, recursively, to the same level of Directory A. So you'd end up with:

someproject/results/2012/2012-02/2012-02-25/name/files

someproject/results/2012/2012-02/2012-02-24/name/files

etc.

I want this script to be future proof though, meaning I don't want the 2012 hardcoded. Also, towards the end of a month you will potentially have data from two different months and both need to be copied into the 2012 directory. So here is the command I used in the shell script file:

CONS="/someproject";
ROOT="/test";

/bin/cp -r ${ROOT}/results/* ${CONS}/results/*

but this resulted in:

/final/results/2012/2012-02/2012-02-25/name/files

and

/final/results/2012/2012/2012-02/2012-02-24/name/files

So as I hope is clear, it started a level below where I wanted it too. Can anyone fill me in on what I'm doing wrong, if they can understand what I'm even trying to explain. My apologies if it's not clear. I'm sure this is a fairly simple fix but I'm not sure what to do. Shell scripting is not a strong point of mine.

like image 559
cardician Avatar asked Aug 26 '26 16:08

cardician


1 Answers

One poster suggests rsync, which is overkill.

cp -rp will work fine. if you want to move the files, just mv the directory -- it and everything under it will move too.

The only real problem here is the use of terminating *'s in the command line in the original script. You don't need the *, you're just trying to pass directories to the cp command, you aren't trying to pass it the names of all the files already in the source (and more importantly, the destination).

like image 79
Perry Avatar answered Aug 30 '26 23:08

Perry



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!