Sign up ×
Unix & Linux Stack Exchange is a question and answer site for users of Linux, FreeBSD and other Un*x-like operating systems. It's 100% free, no registration required.

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

share|improve this question
    
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 Aug 21 '14 at 18:26
    
You are right. Typo :) Thank you –  Tesly Aug 21 '14 at 18:30

2 Answers 2

up vote 4 down vote accepted

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)
share|improve this answer

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
share|improve this answer
    
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 –  val0x00ff Aug 21 '14 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 Aug 21 '14 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. –  val0x00ff Aug 21 '14 at 18:44

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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