Reputation: 398
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
Upvotes: 3
Views: 1053
Reputation: 204731
arr=( $(awk '/MemFree/{split($0,a)} END{print a[2], a[4]}' /proc/meminfo) )
echo "${arr[0]}"
echo "${arr[1]}"
Upvotes: 0
Reputation: 104111
BTW: If you print multiple vales 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 either need a comma:
$ echo "11 22" | awk '{print $1,$2}'
11 22
Or physicality:
$ echo "11 22" | awk '{print $1" "$2}'
11 22
Because without separation, the command substitution not 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
Upvotes: 0
Reputation: 786359
Using BASH
you can reduce your complex commands to this:
read -r _ numA _ numB < <(grep MemFree /proc/meminfo | tail -n 1)
Upvotes: 3
Reputation: 896
Assign the output directly to your variable:
var=$(cat /proc/meminfo | grep "MemFree" | tail -n 1 | awk '{ print $2 $4 }')
echo $var
Upvotes: 4