我的脚本有问题
它是一个通知程序,会在特定时间向我发送电子邮件,然后在文件超过 100kb 时包含一条声明
这是我的脚本,我如何配置它以便它向我发送通知?
#!/bin/bash
file="afile"
maxsize=100
while true; do
actualsize=$(du -k "$file" | cut -f1)
if [ $actualsize -ge $maxsize ]
then
echo size is over $maxsize kilobytes
subject="size exceed on file $file"
emailAddr="[email protected]"
emailCmd="mail -s \"$exceedfile\" \"$emvpacifico\""
(echo ""; echo "date: $(date)";) | eval mail -s "$exceedfile" \"[email protected]\"
exit
else
echo size is under $maxsize kilobytes
fi
sleep 60
done
答案1
快速重写,内嵌注释:
#!/bin/bash
file="afile"
maxsize=100
while true; do
# Use `stat`, the tool for getting file metadata, rather than `du`
# and chewing on its output. It gives size in bytes, so divide by
# 1024 for kilobytes.
actualsize=$(($(stat --printf="%s" "$file")/1024))
if [[ $actualsize -ge $maxsize ]]; then
echo "size is over $maxsize kilobytes"
subject="size exceed on file $file"
emailAddr="[email protected]"
# In almost all cases, if you are using `eval`, either
# something has gone very wrong, or you are doing a thing in
# a _very_ suboptimal way.
echo "Date: $(date)" | mail -s "$subject" "$emailAddr"
else
echo "size is under $maxsize kilobytes"
fi
sleep 60
done
另外,我建议不要运行无限循环的脚本,而是将脚本更改为仅运行一次,并安排它使用cron
表条目运行。