Reputation: 13
I'm making a bash script that should backup all files and dir structure to another dir. I made the following code to do that:
find . -type f -exec cp {} $HOME/$bdir \; -o -type d -exec mkdir -p {} $HOME/$bdir \; ;
The problem is, is that this only copies the files and not the dir structure.
NOTE: I may not use cp -r
, cp -R
or something like it because this code is part of an assignment.
I hope somebody can put me in the right direction. ;)
Joeri
EDIT:
I changed it to:
find . -type d -exec mkdir -p $HOME/$bdir/{} \; ;
find . -type f -exec cp {} $HOME/$bdir/{} \; ;
And it works! Ty guys ;)
Upvotes: 1
Views: 665
Reputation: 45057
This sounds like a job for rsync.
You mention that this is an assignment. What are your restrictions? Are you limited to only using find
? Does it have to be a single command?
One way to do this is to do it in two find
calls. The first call only looks for directories. When a directory is found, mkdir
the corresponding directory in the destination hierarchy. The second find
call would look for files, and would use a cp
command like you currently have.
You can also take each filename, transform the path manually, and use that with the cp
command. Here's an example of how to generate the destination filename:
> find . -type f | sed -e "s|^\./|/new/dir/|"
/new/dir/file1.txt
/new/dir/file2.txt
/new/dir/dir1/file1_1.txt
/new/dir/dir1/file1_2.txt
For your purposes, you could write a short bash script that take the source file as input, uses sed
to generate the destination filename, and then passes those two paths to cp
. The dirname
command will return the directory portion of a filename, so mkdir -p $(dirname $destination_path)
will ensure that the destination directory exists before you call cp
. Armed with a script like that, you can simply have find
execute the script for every file it finds.
Upvotes: 1
Reputation: 2504
Can you do your find
with "-type d" and exec a "mkdir -p" first, followed by your find that copies the files rather than having it all in one command? It should probably also be mkdir -p $HOME/$bdir/{}.
Upvotes: 0