如果内存达到 80%,需要触发脚本

Need to trigger a script if Memory reaches 80 %

我有一个使用 HeapDump 的 bash 脚本。但是我需要在我的机器内存达到80%时自动触发这个。

谁能帮我写剧本?我在 AWS 上有我的环境 运行。

这是我目前的尝试:

#!/bin/bash
threshold=40
threshold2=45
freemem=$(($(free -m |awk 'NR==2 {print }') * 100))
usage=$(($freemem / 512))
if [ "$usage" -gt "$threshold" ]

shell 的工作方式是检查每个程序的退出代码以决定下一步做什么。因此,您想重构您的代码,以便当内存低于 80% 时 returns 0(成功),否则为其他数字。

在 shell 中做算术充其量是脆弱的,如果你想要浮点数而不是整数,那是不可能的。您已经在使用 Awk - 为了简单和高效,将所有逻辑重构到 Awk 中。

#!/bin/bash
# declare a function
freebelowthres () {
    free -m |
    awk -v thres="" 'NR==2 {
        if ( * 100 / 512 > thres) exit(1)
        exit(0) }'
}

用法:if freebelowthres 80; then...