Peter Black
Peter Black

Reputation: 1172

Why can't I assign the value returned by grep to a variable?

I have tried:

TOTAL_MEM= $(grep MemTotal /proc/meminfo | awk '{print $2}')
TOTAL_MEM= 'grep MemTotal /proc/meminfo | awk '{print $2}''
TOTAL_MEM= grep MemTotal /proc/meminfo | awk '{print $2}'

and every time I call:

echo "Total memory available: " $TOTAL_MEM

It just returns blank.. What did I miss?

Upvotes: 1

Views: 90

Answers (1)

Jotne
Jotne

Reputation: 41450

Cred to Anubhava for posting this first, but here is a good way to do it:

TOTAL_MEM=$(awk '/MemTotal/ {print $2}' /proc/meminfo)

Does not work since there are space after =

TOTAL_MEM= $(grep MemTotal /proc/meminfo | awk '{print $2}')

Does not work since there are space after = and wrong quoting. Use parentheses or backtics. (Best to use parentheses)

TOTAL_MEM= 'grep MemTotal /proc/meminfo | awk '{print $2}''

Does not work since there are space after = and missing quoting.

TOTAL_MEM= grep MemTotal /proc/meminfo | awk '{print $2}'

Upvotes: 2

Related Questions