I'm using Ubuntu 16.04 and I created a sh file.
cd /home/malus
echo "______________________________________________________________________" >> /home/malus/top.txt
date >> /home/malus/top.txt
sudo top n 1 o %MEM u mysql | grep mysql >> /home/malus/top.txt
I want to save the information of MySQL into a file (top.txt) + date + seperator
When I run the sh file all is correct and the output file contains 3 lines.
But, when I let crontab to run the script the output file does not contain the top output and instead I have an empty line (I have seperator + date but not top output).
For crontab I used this command:
sudo crontab -e
And the contents are:
00 * * * * /home/malus/top.sh
15 * * * * /home/malus/top.sh
30 * * * * /home/malus/top.sh
45 * * * * /home/malus/top.sh
Edited Part:
The output when I run the script file directly (./top.sh), as you see there are some bizarre characters (in Notpad++ they are as ESC)
______________________________________________________________________
Wed Apr 10 11:24:33 EDT 2019
(B[m 636 mysql 20 0 3681720 1.233g 4236 S 0.0 63.3 113:35.71 mysqld (B[m[39;49m[K
The output of crontab, as you see there is no output for top command:
______________________________________________________________________
Wed Apr 10 11:30:01 EDT 2019
ANSWER
I did these changing according to steeldriver and terdon (Thanks to you both)
The script file:
echo "______________________________________________________________________" >> /home/malus/top.txt
date >> /home/malus/top.txt
sudo top n 2 -b o %MEM u mysql | grep mysql >> /home/malus/top.txt
For running the crontab as root:
sudo crontab -e
The crontab contents:
00 * * * * /home/malus/top.sh 2>>/home/malus/top.err
15 * * * * /home/malus/top.sh 2>>/home/malus/top.err
30 * * * * /home/malus/top.sh 2>>/home/malus/top.err
45 * * * * /home/malus/top.sh 2>>/home/malus/top.err
/usr/bin/top
instead oftop
top n 1 o %MEM u mysql | grep mysql
.(B[m
sequences are formatting characters - if you want to avoid them, runtop
in batch mode (top -b
)-b
. Malus, does it work if you usetop b n 1 o %MEM u mysql | grep mysql
? Also, you probably wantn 2
and notn 1
.top -n 1
doesn't show the right output (it's the value since boot, not the current one).