Nk_email_disk_usage

Home

Description

The nk_email_disk_usage() function is a Bash function that displays the disk usage of email accounts on a server. It does this by first finding every email directory on the server, which are directories with a “cur” subdirectory. It then uses awk to extract the email address from each directory path, and for each email address, it calculates the total disk usage and displays it in a table with the email address and its corresponding disk usage. The function uses du to calculate the disk usage and sort to sort the results in descending order of disk usage. Finally, it formats the output as a table using the column command.

Example

No Example at the moment.

Code

nk_email_disk_usage() {
# This is basically just a wrapper for gen_email_disk_usage that does some formatting.

gen_email_disk_usage() {
# First print the table headers.
echo "Email Disk-Usage"
# Going to be honest this is a bit messy. Could be a better way to go about this.
# First find every email directory on the server. Essentially this boils down to  every email account having a "cur" directory.
# the email dirs would look something like /home/nkern/mail/nkern.net/nikki/cur.
# Use awk to remove the cur at the end. So we're working with something like /home/nkern/mail/nkern.net/nikki
# Now for every email_dir we do the following stuff.
for email_dir in $(readlink -f /home/*/mail/*/*/cur | awk '{gsub("cur$",""); print $0}'); do
    # Populate variable used in the table.
    # the email_dir already contains the email address but it's written as a file path
    # So we use awk with the / as the delimeter and print the 3rd to last field, an @ sign and then the 2nd to last field.
    # Which gets us something like "nikki@nkern.net" which we set to the variable $email
    email="$(echo "$email_dir" | awk -F "/" '{print $(NF-1)"@"$(NF-2)}')"

    # Now get the total disk usage of $email_dir.
    # Get the first field of the the du result which is the disk usage total.
    # Set the result of that disk usage to the variable $disk_usage.
    disk_usage="$(du -sh "$email_dir" | awk '{print $1}')"

    # Now print out the table row. using the varilable $email and $disk_usage
    echo "$email" "$disk_usage"
done | sort -rh -k 2
# Once all of the rows have been populated, by highest disk usage first.
}

# Finally run gen_email_disk_usage and format it as a table with column.
gen_email_disk_usage | column -t
}

Author: Nichole Kernreicht

Created: 2023-04-09 Sun 20:59