That code is not particularly clean.
I see
Useless Use Of Grep and long chains of text tools that could be replaced by simpler
awk versions. Except that said commands are also ill-advisedly
parsing ls! Not good.
And since this is a
bash script, the numerical tests should be using
((..)) instead.
I tried to do a bit of re-writing, but I'm stuck over figuring out what two "
ls -al /var/spool/mqueue" lines are supposed to produce. I don't have that directory on my system. I tried to reverse engineer them, but it's just not clear to me what they're doing exactly.
I can already say, at least, that "
sort $5" and "
sort $1" won't work properly, unless those are values input when the script is called, since those will be treated as shell positional parameters.
sort is not
awk. I imagine you want "
sort -n k5,5" instead. The proper syntax for tail is also "
tail -n 1". The "
-1" style is deprecated.
But again, I'm sure there are better ways to get that data anyway.
Anyway, here's what I came up with far:
Code:
#!/bin/bash
mailaddress='frank.nowicki@hovservices.com'
count=$( mailq | awk '/Total requests:/ {print $3}' )
mqlist=( /var/spool/mqueue/* ) ; actualcount=${#mqlist[@]}
#can't fix these two yet (except for sort), but they really need it.
emailvar=$( ls -al /var/spool/mqueue | sort -k5,5n | awk '{print $5}'| uniq -c | sort -k1,1n | -tail -n 1 | awk '{print $2}' )
emailbody=$( ls -al /var/spool/mqueue | grep $emailvar | awk '{print $9}'| head -1 )
emailcat=$( <"$emailbody" )
if (( count >= 50 )); then
mail "$mailaddress" <<-MAILBODY
Mail queue is at: $count
Actual count of mail que directory is: $actualcount
Please check mailq directory for file size of $emailvar
$emailcat
MAILBODY
if (( actualcount > 300 )); then
rm /var/spool/mqueue/[qd]f*
fi
fi
exit 0
Note the use of '
<<-' in the
here document. The extra '-' means that you can indent the body of it with initial tab characters, to help with script formatting. These will be removed during execution and won't be included in the mail itself. They must be
tabs though, not spaces!