1833415 Members
3307 Online
110052 Solutions
New Discussion

Re: Script error in du

 
SOLVED
Go to solution
Chern Jian Leaw
Regular Advisor

Script error in du

I have a txt file of the following format:
#cat du.txt
/home
/etc
/sbin
...

I would like to write a script to calculate the disk usage of these filesystems. I did it as follows:
#cat du.sh
#!/bin/sh
for i in `cat du.txt`
do
$all+=du $i
done
echo $all

The shell complained of an undefined variable $all. Purpose of $all is to have a grand total of the entire disk usage of the filesystems specified in du.txt.

Could someone help please help out? Please feel free to also comment on other more efficient ways of performing the same task.

Thanks.

4 REPLIES 4
steven Burgess_2
Honored Contributor
Solution

Re: Script error in du

Hi Chern

I would use the following

You have your files in /tmp/calc

/home
/usr

Then have script calc1

#!/usr/bin/sh
calc=/tmp/calc
for file in $(cat $calc)
do
du -sk $file | awk '{ print $1 }' >> /tmp/calc2
done
cat /tmp/calc2 | awk 'BEGIN {total=0;} {total=total+$1;} END {print total,"\n";}
' > /tmp/calc3


Regards

Steve

take your time and think things through
S.K. Chan
Honored Contributor

Re: Script error in du

First lets fix your script ...

#!/bin/sh
tot=0
for i in `cat du.txt`
do
((tot=$tot+`du -sk $i|awk '{print $1}'`))
done
echo $tot

You would want to use "du -sk /dirname" so that you get the total of that whole dir in KBytes. Do ..
# man du
for details..
The "awk" statement after the "du" will extract first field .. example
# du -sk /etc
95456 /etc

hope it helps..
S.K. Chan
Honored Contributor

Re: Script error in du

First lets fix your script ...

#!/bin/sh
tot=0
for i in `cat du.txt`
do
((tot=$tot+`du -sk $i|awk '{print $1}'`))
done
echo $tot

You would want to use "du -sk /dirname" so that you get the total of that whole dir in KBytes. Do ..
# man du
for details..
The "awk" statement after the "du" will extract first field .. example
# du -sk /etc
95456 /etc
steven Burgess_2
Honored Contributor

Re: Script error in du

Hi Chern

I would use the following

You have your files in /tmp/calc

/home
/usr

Then have script calc1

#!/usr/bin/sh
calc=/tmp/calc
for file in $(cat $calc)
do
du -sk $file | awk '{ print $1 }' >> /tmp/calc2
done
cat /tmp/calc2 | awk 'BEGIN {total=0;} {total=total+$1;} END {print total,"\n";}
' > /tmp/calc3


Regards

Steve

take your time and think things through