Reading a variable from AWK

I am trying to get memory information with this command:

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

      

I get this

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

      

My attempts to read this data for a variable were unsuccessful. My question is, how can I read this to variables? I want to read how much memory is free: 90841312 KB

Hello

+3


source to share


4 answers


By using BASH

, you can reduce your complex commands:



read -r _ numA _ numB < <(grep MemFree /proc/meminfo | tail -n 1)

      

+3


source


Assign the output directly to your variable:



var=$(cat /proc/meminfo | grep "MemFree" | tail -n 1 | awk '{ print $2 $4 }')
echo $var

      

+4


source


BTW: If you are printing multiple values ​​from awk you need a separator:

$ echo "11 22" | awk '{print $1 }'
11
$ echo "11 22" | awk '{print $2}'
22
$ echo "11 22" | awk '{print $1 $2}'
1122
 ^ note no space there...

      

You need a comma:

$ echo "11 22" | awk '{print $1,$2}'
11 22

      

Or physicality:

$ echo "11 22" | awk '{print $1"    "$2}'
11    22

      

Since no separation, command substitution doesn't read what you intend:

$ read -r f1 f2 <<< $(echo "11 22" | awk '{print $1 $2}')
$ echo $f1
1122
echo $f2

# f1 got two fields and nada for f2

      

0


source


arr=( $(awk '/MemFree/{split($0,a)} END{print a[2], a[4]}' /proc/meminfo) )
echo "${arr[0]}"
echo "${arr[1]}"

      

0


source







All Articles