0

Here is the script:

TYPE="${BLOCK_INSTANCE:-mem}"

awk -v type=$TYPE '
/^MemTotal:/ {
    mem_total=$2
}
/^MemFree:/ {
    mem_free=$2
}
/^Buffers:/ {
    mem_free+=$2
}
/^Cached:/ {
    mem_free+=$2
}
/^SwapTotal:/ {
    swap_total=$2
}
/^SwapFree:/ {
    swap_free=$2
}
END {
    if (type == "swap") {
        free=swap_free/1024/1024
        used=(swap_total-swap_free)/1024/1024
        total=swap_total/1024/1024
    } else {
        free=mem_free/1024/1024
        used=(mem_total-mem_free)/1024/1024
        total=mem_total/1024/1024
    }
    pct=used/total*100

    # full text
    printf("%.1fG/%.1fG (%.f%)\n", used, total, pct)

    # short text
    printf("%.f%\n", pct)

    # color
    if (pct > 90) {
        print("#FF0000\n")
    } else if (pct > 80) {
        print("#FFAE00\n")
    } else if (pct > 70) {
        print("#FFF600\n")
    }
}
' /proc/meminfo

Here is the error when I try to run it:

$ ./memory 
awk: run time error: not enough arguments passed to printf("%.1fG/%.1fG (%.f%)
")
    FILENAME="/proc/meminfo" FNR=46 NR=46
1.1G/15.3G (7

It prints what I want (the memory usage) but also has an error.

Can anyone help?

| improve this question | | | | |
5

Awk's printf is treating your trailing % as the start of a fourth format specifier. If you want to print a literal % sign you need %%, for example

$ awk 'BEGIN{printf("%.1fG/%.1fG (%.f%%)\n", 1.2, 3.4, 5.6)}'
1.2G/3.4G (6%)
| improve this answer | | | | |
1

It seems that you used mawk, which does not support print % literally when it does not have valid format.

Change the lines which have trailing % to:

# full text
printf("%.1fG/%.1fG (%.f%%)\n", used, total, pct)

# short text
printf("%.f%%\n", pct)

or switch to gawk or nawk, which will output % as-is if does not followed by valid format conversion.

| improve this answer | | | | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.