Shell script to loop and store in array

I'm trying to achieve the follwoinig with no luck.

Find the directories that are greater than 50GB in size and pick the owner of the directory as I would like to send an alert notification.

du -sh * | sort -rh

139G     Dir_1
84G     Dir_2
15G     Dir_3

ls -l Dir_1

drwx------ 2 User1 Group1  4096 Aug 15 16:38 Dir_1

The script should resolve for Dir_1 and Dir_2 as the size is > 50GB and send a notification to User1 and User2 indicating that the directores have exceed the limit.

Apprecaiet any help.

---------- Post updated at 05:54 PM ---------- Previous update was at 04:48 PM ----------

I tried this.

#!/bin/ksh
dir_name=/apps/directory_name

cd $dir_name

du_cmd=`du -sh * | sort -rh`

for f in $du_cmd
do
echo $f
done

Output:

138G
Dir_1
76G
Dir_2
15G
Dir_3
1.7G

--------
I added bit more functionality

#!/bin/ksh
dir_name=/apps/directory_name

cd $dir_name

du_cmd=`du -sh * | sort -rh`

for f in $du_cmd
do
echo $f

echo `ls -ld $dir_name/$f | awk '{print$3}'`

done

Output:

156G
ls: cannot access /apps/directory_name/156G: No such file or directory

Dir_1
User_1
76G
ls: cannot access /apps/directory_name/76G: No such file or directory

Dir_2
User_2
15G
ls: cannot access /apps/directory_name/15G: No such file or directory

Dir_3
User_3
1.7G
ls: cannot access /apps/directory_name/1.7G: No such file or directory

Please help.

Not tested..

this script will check the directory size is in GB and if its more than 50GB then it get the corresponding userid in for loop. implement your notification method in for loop

#!/bin/bash

dir_name=/apps/directory_name
cd ${dir_name}

du -sh * | awk '$1~/G/ && $1+0>50' | while read SIZE DIR_NAME
do
	USER_ID=$(ls -ld ${DIR_NAME} | awk '{print $3}')
	echo "Send Notification to ${USER_ID}"
	# Put your mail command here
done
1 Like

That might work, but it will only find directories that contain 51 through 999 Gb. It would not report on directories that have crossed over the 1 Tb threshold.

Using human readable numbers (i.e. du -h ) when looking for numbers is frequently more trouble that it is worth. You might want to use:

du -sk * | awk '$1+0>50*1024*1024' | ...

instead.

1 Like

Thanks for the inpurts - I really appreciaet it. I will try and keep you posted.