LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (http://www.linuxquestions.org/questions/programming-9/)
-   -   Comparing file sizes using a bash script. (http://www.linuxquestions.org/questions/programming-9/comparing-file-sizes-using-a-bash-script-126372/)

IanChristie 12-16-2003 12:09 PM

Comparing file sizes using a bash script.
 
I'm learning bash scripting (the hard way, diving right in.) I'm making a script that compresses files and when the directory reaches a capacity (around 650-700MB) burn the data to cd.

My question is , how do I check the size of a directory in a bash script?

druuna 12-16-2003 12:22 PM

Take a look at the du command.

$ du -h -s /home/
484M /home

The above command will count all subdirs too. The following command does not:

$ du -S -s -h /home
4.0K /home

See the manpage for more options.

IanChristie 12-19-2003 11:00 AM

Quote:

Originally posted by druuna
Take a look at the du command.

$ du -h -s /home/
484M /home

The above command will count all subdirs too. The following command does not:

$ du -S -s -h /home
4.0K /home

See the manpage for more options.

Thanks, that's the first part that I need now :) but I'm still stuck, how do I get the numerical value into a variable. I can get the entire output into a variable.

Using your first example

484M /home

how do I get the 484 by itself so I can compare? I've been to several sites with great looking tutorials, but they all seem to lack clarity, I'm finding them confusing and they don't show examples useful to me.

Thanks for the help.

druuna 12-19-2003 11:36 AM

The fieldseperator option is the key to this problem, some of the tools support this (cut, awk to name 2). When you don't set the fieldseperator a space (and sometimes a tab) are default.

The seperator needed in this case isn't one specific character:

484M /home <= The M would be the seperator, but there could also be a G or a K.

awk supports regular expressions in the fieldseperator field (-F). So here's the solution:

$ du -h -s /home/
539M /home

$ du -h -s /home/ | awk -F"[GKM]" '{ print $1 }'
539

Maybe there's an easier way to do this, this just came to mind first.

unSpawn 12-19-2003 01:24 PM

Here's another example, w/o awk. Only things it depends on are AFAIK a "regular" IFS and the flags for "df" cuz it only cuts the last char:
s=( $(du -h -s /home) ); let i=${#s[0]}-1; s=${s[0]:0:$i}
echo "Size is $s megs"

IanChristie 12-19-2003 10:14 PM

Thanks for the help, those are both great ways, unSpawn's one worked out easier in my circumstance.

Thanks again.


All times are GMT -5. The time now is 03:54 PM.