5

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

#!/bin/bash
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

1
  • On my system, meminfo only has one line with MemFree and it only has three columns. Are you sure you don't want your awk to be '{ print $2 $3 }'?
    – drs
    Commented Aug 21, 2014 at 18:26

2 Answers 2

4

You can use read and simply do the following

while read -r memfree
  do printf '%s\n' "$memfree"
  done < <(awk -F: '/MemFree/{print $2}' /proc/meminfo)
3

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
3
  • You can use /MemFree/ in awk regex pattern which does the same as grep is doing. No need to start another process. Also cat is not necessary since awk can read too. So you could remove cat and grep and do everything just by awk Commented Aug 21, 2014 at 18:32
  • Thanks @val0x00ff, I've taken your cat suggestion. I feel like using /MemFree/ regex in awk is well covered in your answer and at this point I'd be copying it too much.
    – drs
    Commented Aug 21, 2014 at 18:40
  • that's fine. I learn new things by day too. It is good to see different approaches! Thansk for sharing as well. Commented Aug 21, 2014 at 18:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .