Shell Script to find largest file in a directory
Program
echo "Enter the directory name: "
read dir1
#If the directory doesn't exist
if [ ! -d $dir1 ];then
echo "Invalid directory!"
exit
fi
large=0;
#Finds all files recursively in the directory
for file1 in `find $dir1 -type f`
do
#Gets the size and allots it to "large" if it is the largest
size1=`stat -c %s $file1`
echo "Size of $file1 is: $size1"
if [ $size1 -gt $large ];then
large=$size1
lar_file=$file1
fi
done
echo "The largest file is: $lar_file and its size is: $large"
Output
$ sh find-largest-file-in-directory.sh
Enter the directory name:
Documents
Size of Documents/mysql-connector-java-5.0.8.zip is: 8795408
Size of Documents/image.jpg is: 4539
Size of Documents/Computer-Networks--Network.ppt is: 4982784
Size of Documents/PDFs/mysqld-5.7-com-en.pdf is: 264069
Size of Documents/PDFs/Advanced-IP-MPLS-VPN.pdf is: 631151
The largest file is: Documents/mysql-connector-java-5.0.8.zip and its size is: 8795408