Calculating the percentage of the total available memory on linux as an integer in bash
Here is a bash script that is calculating 80% of the total RAM available as an integer on a Linux box:
server_ram_mb=$(awk '/MemTotal/ {printf( "%.2f\n", $2 / 1024)}' /proc/meminfo)
echo "($server_ram_mb * 0.8)/1" | bc > /tmp/output
eighty_percent_ram_mb=$(cat /tmp/output)
However, there are a few things I don't like about this:
- It writes to a temp file (I tried setting it to a variable and couldn't get past syntax issues)
- It requires
bc
, which isn't installed by default on all Linux distros
How can I rewrite/simplify this to avoid those issues?
Solution 1:
eighty_percent_ram_mb=$(free -m | awk 'NR==2{printf "%d", $2*0.8 }')
Should do the job :)