【问题标题】:Why does mailx send a previous version of its referenced file instead of the latest one?为什么 mailx 发送其引用文件的早期版本而不是最新版本?
【发布时间】:2021-08-28 01:46:05
【问题描述】:

我创建了一个简单的脚本,它会自动终止前 2 个进程。但在重新启动之前,我将前 10 个进程列表写入一个文本文件及其内存状态(free -h),然后它会杀死前 2 个进程。但是,当它发送电子邮件时,它不会使用最新的文件,而是使用最后更新的文件。每次运行脚本时都会覆盖 txt 文件。

file=$aa_dir/tst_topprocess.txt #file for top processes
file_chk=$aa_dir/tst_membefore.txt #file for previous memory check
topproc=$(more "$file")
memchk=$(more "$file_chk")


 if [[ "$memtst" -le  "$threshold" ]]; then #for testing
    echo -e "`date` \n $top" > $file  #writes top processes before to a file
    echo -e "`date` \n $chk" > $file_chk #writes free -h results to a file
    #sleep 5
    #restart here
    echo "Killing PIDs..."
    #kill -9 $pid1 $pid2
    sleep 5
    echo -e  Memory check before restart: \n \n $memchk  \n \n Top processes before the restart: \n \n $topproc \n \n Processes after the restart: \n \n $top \n \n `date`" | mailx -s "$subject" -r "$mail_from" abc@gmail.com

结果是: 它确实在杀死pid之前保存了进程,但是当它发送电子邮件时,它没有得到最新的文件。它发送上一次运行的内容。

因此,例如,如果脚本通过 cronjob 每 15 分钟运行一次,则在晚上 11:00 运行的电子邮件正文中显示的文件将是晚上 10:45。

我错过了什么?如何告诉脚本获取最新保存的文件?

【问题讨论】:

  • memchk=$(more "$file_chk") -> echo $memchk?你会期待memchk“自动更改”吗?
  • Memchk 会在每次运行脚本时发生变化。我将其保存在文本文件中的原因是因为我想在重新启动之前和之后查看 pid。我还使用了 nore 以便 memcheck 生成的文件将显示在电子邮件正文中
  • Memchk would change everytime the script is ra 但你这样做 memchk=$(.. file_chk) 然后你这样做 echo -e "date` \n $chk" > $file_chk``。|| 请不要使用反引号 - 改用$(..)。使用shellcheck.net检查您的脚本
  • 是的!那是我应该做的。谢谢!更正了这部分,所以现在它可以正确显示了。 topproc=$(echo -e "date \n $top" > "$file") memchk=$(echo -e "date \n $chk" > "$file_chk") topproc2=$(more " $file") memchk2=$(more "$file_chk")

标签: bash unix scripting


【解决方案1】:

根据@KamilCuk 的建议,我更改了这部分代码以解决问题

topproc=$(echo -e "date \n $top" > "$file") memchk=$(echo -e "date \n $chk" > "$file_chk") topproc2=$(更多 "$file") memchk2=$(more "$file_chk")

【讨论】:

    猜你喜欢
    • 2023-03-04
    • 1970-01-01
    • 1970-01-01
    • 2012-05-28
    • 1970-01-01
    • 2016-07-24
    • 1970-01-01
    • 1970-01-01
    • 2015-10-08
    相关资源
    最近更新 更多