I am writing the top command output to a text file.
I am trying to write a simple bash script to calculate the percentage of used memory and send an
email if the memory used percentage exceeds, say 90%.
Here is the bash script I have thus far.
#!/bin/bash
top -n 1 -b | grep "Mem" > /home/modadm/top-output.txt
MAXMEM=/home/modadm/top-output.txt | grep "Mem" | cut -c 7-14
USEDMEM=/home/modadm/top-output.txt | grep "Mem" | cut -c 25-31
$USEDPCT='echo $USEDMEM / $MAXMEM * 100 | bc'
$USEDPCT | mail -s "Test Email from MOD Server" test@test.com
When I save and execute the script, I get the error “No such file or directory”:
-bash-3.2$ ./memcheck.sh
./memcheck.sh: line 4: =echo $USEDMEM / $MAXMEM * 100 | bc: No such file or directory
Null message body; hope that's ok
-bash-3.2$
Can someone assist? I am a newbie to bash scripting and this is my first script.
Thank you
You have a few problems here.
First, this doesn’t do what you want it to do.
You can’t pipe a filename into a command. You actually want to pipe the contents of the file into the command. You can do that with ‘cat’. However, grep is actually designed to search within a file so you can do
Note that $(cmd) is how you execute a command in a subshell. i.e., you can run some commands to compute the value of a variable in your script. You can also use `cmd` (backticks; usually on the tilde key) but that syntax is less clear.
Again, you probably want to calculate this result in a subshell. Also, don’t use $ when assigning to variables.
This can be rewritten as
Finally, you want to pipe the contents of the variable into the mail program. The pipe is expecting a program to be on the left hand side. You do this by echo’ing the value of the variable into the pipe.
To put everything back together: