Problem with read variable from AWK

I’m trying to get memory info by this command:

set -x
cat /proc/meminfo | grep "MemFree" | tail -n 1 | awk '{ print $2 $4 }' | read numA numB
echo $numA

I’m getting this

+ awk '{ print $2 $4 }'
+ read numA numB
+ tail -n 1
+ grep MemFree
+ cat /proc/meminfo
+ echo

My attempts to read these data to variable were unsuccessful. My question is how I can read this to variables? I want to read how many memory is free like: 90841312 KB

Asked By: Tesly


Try saving single values directly to each variable. You can also remove the cat and the tail pipe by using the -m flag with grep:

numA=$(grep -m 1 "MemFree" /proc/meminfo | awk '{ print $2 }')
numB=$(grep -m 1 "MemFree" /proc/meminfo | awk '{ print $3 }')

echo $numA $numB
Answered By: drs

You can use read and simply do the following

while read -r memfree
  do printf '%sn' "$memfree"
  done < <(awk -F: '/MemFree/{print $2}' /proc/meminfo)
Answered By: Valentin Bajrami
Categories: Answers Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.