Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read variable from AWK

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

Regards

like image 302
Narkon Avatar asked Mar 29 '26 21:03

Narkon


2 Answers

Assign the output directly to your variable:

var=$(cat /proc/meminfo | grep "MemFree" | tail -n 1 | awk '{ print $2 $4 }')
echo $var
like image 191
Beggarman Avatar answered Apr 01 '26 11:04

Beggarman


Using BASH you can reduce your complex commands to this:

read -r _ numA _ numB < <(grep MemFree /proc/meminfo | tail -n 1)
like image 29
anubhava Avatar answered Apr 01 '26 10:04

anubhava



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!