Devin
Devin

Reputation: 277

Linux basic script to print free and total memory

I'm trying to teach myself some basic scripting and unable to use the awk command properly. I want to show the current free and total memory available in MB from the free -m command. However, I keep getting an error that I'll post below. Why is this?

syswatch:

#!/bin/bash

# Use free command to show current free and total memory available in MB

free -m | awk `{print "Free/Total Memory : $3 / $1 MB"}`

Output / Error:

[root@testit /root]# ./syswatch
./syswatch: {print: command not found
Usage: awk [POSIX or GNU style options] -f progfile [--] file ...
        awk [POSIX or GNU style options] [--] 'program' file ...
POSIX options:          GNU long options:
        -f progfile             --file=progfile
        -F fs                   --field-separator=fs
        -v var=val              --assign=var=val
        -m[fr] val
        -W compat               --compat
        -W copyleft             --copyleft
        -W copyright            --copyright
        -W help                 --help
        -W lint                 --lint
        -W lint-old             --lint-old
        -W posix                --posix
        -W re-interval          --re-interval
        -W source=program-text  --source=program-text
        -W traditional          --traditional
        -W usage                --usage
        -W version              --version

To report bugs, see node `Bugs' in `gawk.info', which
is section `Reporting Problems and Bugs' in the
printed version.

Expected output:

Free/Total Memory : 133/190 MB

Upvotes: 0

Views: 985

Answers (1)

Matteo
Matteo

Reputation: 14930

It seems you want the percentage

free -m | sed 1d | awk '{print "Free/Total Memory ", $1, " ", $3 /  $2}'

Your problems

  • You are using backticks (used to execute a sub shell)
  • You are also evaluating the header of the output of free: sed 1d deletes the first line
  • You are dividing the wrong columns: $1 is the memory type, $2 is the total and $3 is the used memory

If the / sign is not a division (see your comment) then

free -m | sed 1d | awk '{printf "Free/Total Memory %s %s/%sMB\n", $1, $3, $2}'

Upvotes: 1

Related Questions