No need to call awk
in your case because Perl is quite good at splitting and printing certain lines itself. Your code has some issues:
The code qx("df -h |awk \+\$5>=70 {print \$6} ")
tries to execute the string "df -h | awk ..."
as a command which fails because there is no such command called "df -h | awk"
. When I run that code I get sh: 1: df -h |awk +>=70 {print } : not found
. You can fix that by dropping the quotes "
because qx()
already is quoting. The variable $test
is empty afterwards, so the chdir
changes to your $HOME
directory.
Then you'll see the next error: awk: line 1: syntax error at or near end of line
, because it calls awk +\$5>=70 {print \$6}
. Correct would be awk '+\$5>=70 {print \$6}'
, i.e. with ticks '
around the awk
scriptlet.
As stated in a comment, df -h
splits long lines into two lines. Example:
Filesystem 1K-blocks Used Available Use% Mounted on
/long/and/possibly/remote/file/system
10735331328 10597534720 137796608 99% /local/directory
Use df -hP
to get guaranteed column order and one line output.
The last system
call shows the directory usage (space) for all lines containing the letter G
. I reckon that's not exactly what you want.
I suggest the following Perl script:
#!/usr/bin/env perl
use strict;
use warnings;
foreach my $line ( qx(df -hP) ) {
my ($fs, $size, $used, $avail, $use, $target) = split(/\s+/, $line);
next unless ($use =~ /^\d+\s*\%$/); # skip header line
# now $use is e.g. '90%' and we drop the '%' sign:
$use =~ s/\%$//;
if ($use > 70) {
print "almost full: $target; top 5 directories:\n";
# no need to chdir here. Simply use $target/* as search pattern,
# reverse-sort by "human readable" numbers, and show the top 5:
system("du -hs $target/* 2>/dev/null | sort -hr | head -5");
print "\n\n";
}
}