Last updated on November 22nd, 2024 at 10:47 am

Script works to check the size of a file passed as a command-line argument, provides its size in bytes or kilobytes and display it in KB (Kilo Bytes). To check the size of a file, you must provide the file name as an argument, and the script will return its size in both Bytes and Kilobytes (KB).

Save the file as filesize.pl

#!/usr/bin/perl -w

use strict;

# Check if the filename argument is provided
if (@ARGV == 0) {
    print "Please pass the name of a file as an argument to check its size.\n";
    exit 1;
}

my $filename = $ARGV[0];

# Check if the file exists and is readable
if (!-e $filename) {
    print "The file '$filename' does not exist.\n";
    exit 1;
}
if (!-r $filename) {
    print "The file '$filename' is not readable.\n";
    exit 1;
}

# Get the file size
my $filesize = -s $filename;

if ($filesize == 0) {
    print "The file '$filename' is empty (0 bytes).\n";
} else {
    printf "Size of the file '$filename': %d Bytes\n", $filesize;
    printf "Size of the file '$filename': %.2f KB\n", $filesize / 1024;
}

Functionality:

  1. Check for Arguments: If no arguments are passed, it informs the user to pass a filename.
  2. File Size Retrieval: Uses the -s operator to get the size of the specified file.
  3. Check for Empty File: If the size is 0, it prints a message stating the file is empty.
  4. Size Conversion: Outputs the size of the file in bytes and kilobytes.

Output

root@production-server:~# ./filesize.pl
Please pass the name of file as an argument to check its size
root@production-server:~# ./filesize.pl  email.sh
Size of the file email.sh is 0.3056640625 Bytes
Size of the file email.sh is 0.3056640625 KB
root@production-server:~# ./filesize.pl data_2022-06-10_17_18_21.sql
Size of the file data_2022-06-10_17_18_21.sql is 345305.563476562 Bytes
Size of the file data_2022-06-10_17_18_21.sql is 345305.563476562 KB
root@production-server:~#