More on bash scripting

This was one of my homework assignments for DevTech on Linux:

Write a script that parses the output of /usr/bin/free and checks if the “free” memory is below 400000 (these are kB). If it is, print a warning that the system is running low on memory. Example run: 

./memory_monitor.sh Memory low: 169416 / 400000 

Parsing  /usr/bin/free:

/usr/bin/free:

**Note: free memory is Mem row and the 4th column

You can use grep Mem to get only the row with mem

Afterwards, you can use awk in order to only get the 4th column

Then, you can compare it to 400000. But since it is an integer comparison, we must use the byte comparator which is -lt (yes bash is weird).

**Some other things to note:

-to get the memory, we must surround the execution with $() to store in variable

-when referring back to the variable, we must access with $

-when making if comparisons, there must be a space after and before the [ and ] brackets

-after an if statement is opened, it must be closed with fi

Bash script that I wrote: 

#!/bin/bash

free_mem=$(/usr/bin/free|grep “Mem”|awk ‘{print $4}’)

if [  $free_mem -lt 400000  ]

then

           echo System is running on sufficient memory: $free_mem/400000.

else

           echo System is running on low memory: $free_mem/400000.

fi

To run script:

chmod 744 script.sh

./script.sh

Output: 

Here are my resources on bash syntax for if statements, variables, comparators, etc:

Other Comparison Operators: https://tldp.org/LDP/abs/html/comparison-ops.html

Variables: https://tldp.org/HOWTO/Bash-Prog-Intro-HOWTO-5.html

If Statements: https://ryanstutorials.net/bash-scripting-tutorial/bash-if-statements.php

 

0 comments on “More on bash scriptingAdd yours →

Leave a Reply

Your email address will not be published.