3
\$\begingroup\$

I'm looking for input on the code itself and formatting/style. This script parses the output of df -h on a Linux server and emails the user if the usage percentage is above the threshold (90% in this case).

#!/usr/bin/perl
use warnings;
use strict;
use Mail::Sendmail;
my $svr = `hostname`;
my @output = `df -h`;
my $msg;
my $mailto = '[email protected]';
my $threshold = 90;
sub main
{
 foreach (@output) {
 if (($_ =~ m/(\d+)% (.*)/) && ( 1ドル > $threshold )) {
 chomp($svr); $msg = "$svr: 2ドル volume is 1ドル percent full\n" }
 }
 my %mail = ( To => $mailto,
 From => '[email protected]',
 Subject => "$svr has a full file system",
 Message => $msg
 );
 if ( defined $msg ) {
 sendmail(%mail) or die $Mail::Sendmail::error;
 }
}
main
Jamal
35.2k13 gold badges134 silver badges238 bronze badges
asked Jul 19, 2014 at 16:39
\$\endgroup\$

1 Answer 1

3
\$\begingroup\$

There is a bug here:

foreach (@output) {
 if (($_ =~ m/(\d+)% (.*)/) && ( 1ドル > $threshold )) {
 chomp($svr); $msg = "$svr: 2ドル volume is 1ドル percent full\n" }
 }

If there are more than one partitions full, $msg will contain only the last one. I think you want to append to $msg instead of overwriting. I suggest to rewrite like this:

chomp(my $svr = `hostname`);
foreach (@output) {
 if (m/(\d+)% (.*)/ && 1ドル > $threshold) {
 $msg .= "$svr: 2ドル volume is 1ドル percent full\n";
 }
}

Explanation of other improvements:

  • Removed unnecessary brackets from the if condition
  • Simplified $_ =~ m// to just m// which does the same
  • Instead of chomp($svr) for each line, do it only once, right after initialization
  • Reindented, so it's easier to see the block of code that belongs to the loop

Lastly, you can drop "defined" in if ( defined $msg ) {

answered Jul 19, 2014 at 17:26
\$\endgroup\$
1
  • \$\begingroup\$ All excellent improvements, thanks! I will make these changes to the code. \$\endgroup\$ Commented Jul 19, 2014 at 18:22

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.