Merge directories in bash?

For discussions about programming, programming questions/advice, and projects that don't really have anything to do with Puppy.
Post Reply
Message
Author
ITAmember
Posts: 167
Joined: Sun 13 Sep 2009, 18:50
Location: The middle of a cornfield

Merge directories in bash?

#1 Post by ITAmember »

It's not as easy as cp -r, some of the directories already exist and it won't let me merge them. I currently have this

Code: Select all

# ${1} is source, ${2} is dest
copydir () {
	for FILE in `ls ${1}`;
	do
		OUTDIR=${2}/${FILE}
		FILE=`echo ${1}/${FILE}`
		
		cp -rf ${FILE} ${OUTDIR}
		
		if [ -d  ${FILE} ] ;
		then
			copydir ${FILE} ${OUTDIR}
		fi
	done;
}
but it goes into a infinite recursion. Any tips?

User avatar
dejan555
Posts: 2798
Joined: Sun 30 Nov 2008, 11:57
Location: Montenegro
Contact:

#2 Post by dejan555 »

You want to merge all files from one directory to another?
Just use same method used for installing sfs's (and pets probably):
Let's say you have 2 directories dir1 and dir2:

Code: Select all

cd dir1
cp -a * ../dir2
That easy, and if you don't want to overwrite already existing files in dir2 you can use:

Code: Select all

cd dir1
yes n | cp -ai * ../dir2
puppy.b0x.me stuff mirrored [url=https://drive.google.com/open?id=0B_Mb589v0iCXNnhSZWRwd3R2UWs]HERE[/url] or [url=http://archive.org/details/Puppy_Linux_puppy.b0x.me_mirror]HERE[/url]

ITAmember
Posts: 167
Joined: Sun 13 Sep 2009, 18:50
Location: The middle of a cornfield

#3 Post by ITAmember »

I wish cp --help would've told me that... Thanks. :)

User avatar
dejan555
Posts: 2798
Joined: Sun 30 Nov 2008, 11:57
Location: Montenegro
Contact:

#4 Post by dejan555 »

Now, let's say you have multiple directories to merge, like 5 of them for example, I'd make this kind of dir structure:

./parentdir:
subdir1
subdir2

./parentdir/subdir1:
dir1
dir2
dir3
dir4
dir5

./parentdir/subdir2:

Now, to copy all files from dir1-dir5 to subdir2 and then erase dirs I use this command:

Code: Select all

cd parentdir/subdir1
for i in *; do cd $i; yes n | cp -ai * ../../subdir2/; cd ..; rm -rf $i; done;
puppy.b0x.me stuff mirrored [url=https://drive.google.com/open?id=0B_Mb589v0iCXNnhSZWRwd3R2UWs]HERE[/url] or [url=http://archive.org/details/Puppy_Linux_puppy.b0x.me_mirror]HERE[/url]

Post Reply