tags:

views:

189

answers:

2

I want to copy a folder from my X-Serve RAID to an external HDD on an X-Serve. Both disks are on the same server, so copying is fairly easy. I use the ditto command:

ditto -rsrc /Volumes/WadXServeRaid/Users/ $destinationpath/Users/

However, I only want the copy to start if there is enough space on the destination disk. I know I can use the DU command to assess the destination disk but I don't know how to get the file size of a folder and compare it to the destination space.

Any suggestions would be hugely appreciated!

+2  A: 
du -s name_of_folder_to_be_copied

will give you the total size of the folder and contained items (files and folders). With df you can check the free space on the destination drive. Compare the two sizes, and you're done (be carefull, du gives you the size in bytes, df in 512-bytes blocks, or 1024 bytes if you use the -k option).

Edit: to be more precise, you have to parse the df output. One way to only get the free space (in kB) on the destination disk could be:

df -k mount_point_of_destination|tail -1|sed "s/  */ /g"|cut -d ' ' -f 4

Mind you, you could achieve the same result with awk, for example. I just used sed and cut because that's the first way I thought off right off the bat ;)

lightman
I agree with the general idea. However, there will be trouble in the details, when the numbers are very close: If the destination filesystem has more per-file overhead, the copy might require significantly more space than the original.
ndim
Yes, that's true. One possible way to play it (almost) safe, would be to take the total size of the source folder and increment it by, say, 10% before comparing it to the free space on the destination disk. Obviously, the percentage would have to ideally be determined in such a way that it is high enough to be sure that there is enough space (even if some other user/program is writing to the destination disk), and at the same time low enough not to block a copy that would otherwise complete without error. Provided the fs is the same on both disk, it should pose no problem...
lightman
A: 
#!/bin/bash

######Change These Vars######
srcFolder="/Volumes/WadXServeRaid/Users"
dstFolder="/path/to/some/external/folder/Users"
dstPartition="/dev/hdd1"
overheadbytes=104857600
#############################

dstBytes=$(df -B1 | awk -v dpart="$dstPartition" '$1 ~ dpart {print $4}');
read srcBytes _ < <(du -s "$srcFolder" 2>/dev/null);

if (( $dstBytes > $srcBytes + $overheadBytes )); then
  ditto -rsrc "$srcFolder" "$dstFolder"
fi

Edit

  • Added $overheadBytes with default value of 100MB per comment discussion
  • I didn't pass the partition/mount point as an argument to 'df' on purpose because it seems to require root privileges and I did not want to force such a script to be run as root.
SiegeX