How to compare if the size of the directory is more than 500MB in unix

I use du -sk command to find the size of the directory but when i use the result of 'du -sk' into if statement its throwing error.. Could u solve with this..?

what error ?

show your script

My Script is,

size='du -sh'
$size
size1='30M'
if [ $size -gt $size1 ]
then
  echo "size greater"
else
  echo "size smaller"
fi

its showing

36M     .
size.sh: line 4: [: too many arguments
size smaller

Error

i think du -sh is not correct cmd for that

try this..

 
size=`du -sh`
size=`echo $size | sed 's/.$//'`
size1='30'
if [ $size -gt $size1 ]
then
echo "size greater"
else
echo "size smaller"
fi
1 Like

Yep.. Working !! Thank you

@shaal89

you are using -h option, if your directory size goes to 1 to 29 GB, then the above command will fail. Because you are checking it for MB and we are removing the human readable format in the end ( M or G or K )

i changed the command to 'du -sm' so its working..

"you are using -h option, if your directory size goes to 1 to 29 GB, then the above command will fail. Because you are checking it for MB and we are removing the human readable format in the end ( M or G or K )"

i dont understand this.. Sorry..

 
size=`du -sh`
size=`echo $size | sed 's/.$//'`
size1='30'
if [ $size -gt $size1 ]
then
echo "size greater"
else
echo "size smaller"
fi

In the above script, we are removing the M from 36M.
after that we are checking in the if condition.

say, suppose your directory size is 20G ( 20 GB), in this case, also we are removing the G and comparing with 30. (This is wrong calculation - because the size is in GB, not in MB )

"you are using -h option, if your directory size goes to 1 to 29 GB, then the above command will fail. Because you are checking it for MB and we are removing the human readable format in the end ( M or G or K )"

I dont understand this.. Sorry..
But i use 'du -sm' command.. that is right na..?

if you are using -sm then, its fine. (As it always shows the size in MB )

-m     like --block-size=1M

actually..

size=`du -sh`
size=`echo $size | sed 's/.$//'`
size1='30'
if [ $size -gt $size1 ]
then
  echo "size greater"
else
  echo "size smaller"
fi

This doesnt work for me..
After i change the script to

size=`du -sm`
size=`echo $size | sed 's/.$//'`
size1='30'
if [ $size -gt $size1 ]
then
  echo "size greater"
else
  echo "size smaller"
fi

We are removing only that '.' right.. we are not removing M or G

.$ --> means last character.

 
bash-3.00$ echo "10M" | sed 's/.$//'
10
bash-3.00$ echo ". 10M" | sed 's/.$//'
. 10

---------- Post updated at 12:56 PM ---------- Previous update was at 12:51 PM ----------

can you post the exact output of the below command.

 
du -sm

36 .
is the exact output for du -sm

ok, then its fine.

In this case, it will remove the . (dot)