Today, I gave myself a small task of detecting the total amount of RAM installed on a hardware from a Linux system using a POSIX shell script. I ended up using dmidecode
utility and a rather complex looking code for such a simple task.
Though I found countless simple pieces of code on various places, they are all doing not just that exactly.
I don't want free RAM or total available RAM to the kernel.
I want the pure number of MiBs, which are installed in the hardware (memory sticks).
Reasons are multiple, to name one, for example, there could be less available RAM to the system due to various things, like integrated graphics shared memory, etc.
Performance is not an issue. I know it is slow. I just want to know if there is a way to perhaps simplify the code.
#!/bin/sh
is_number()
{
[ "${1}" -eq "${1}" ] 2> /dev/null
}
ram_size_entries=$ram_entries=$(sudo dmidecode --type 17 | grep Size: | awk '{ print $2 }')
ram_entries_count=$(( $(printf '%s\n' "${ram_entries}" | wc -l) - 1 ))
i=0
ram_entry=0ram_entry=x
total_ram_size_mb=0
while is_number[ "${ram_entryi}" -le "${ram_entries_count}" ]
do
is_number "${ram_entry}" && total_ram_size_mb=$(( total_ram_size_mb + ram_entry ))
i=$(( i + 1 ))
ram_entry=$(echo "${ram_size_entriesram_entries}" | sed --posix --quiet "${i}{p;q}")
done
if [ "${total_ram_size_mb}" -ge 1024 ]
then
echo "Total RAM installed in Gigabytes =" $(( total_ram_size_mb / 1024 ))
else
echo "Total RAM installed in Megabytes = ${total_ram_size_mb}"
fi