Bash script results in different output when running from a cron job

Viewed 129

I'm puzzled by this problem I'm having on Ubuntu 20.04 where cron is able to run a bash script but the overall outcome is different then when using the shell command. I've look through all questions I could in here and on Google but couldn't find anyone that had the same problem.

Background: I'm using Pushgateway to store metrics I'm generating through a bash script, and afterwards it's being imported automatically to Prometheus. The end goal is to export a list of running processes, their CPU%, Mem% etc, similar to top command.

This is the bash script:

    #!/bin/bash
z=$(top -n 1 -bi)
while read -r z
do
   var=$var$(awk 'FNR>7{print "cpu_usage{process=\""$12"\", pid=\""$1"\"}", $9z} FNR>7{print "memory_usage{process=\""$12"\", pid=\""$1"\"}", $10z}')
done <<< "$z"
curl -X POST -H  "Content-Type: text/plain" --data "$var
" http://localhost:9091/metrics/job/top/instance/machine

I used to have a version that used ps aux but then I found out that it only shows the average CPU% per process.

As you can see, the command I'm running is top -n 1 -bi which gives me a snapshot of active processes and their metrcis. I'm using awk to format the data, and FNR>7 because I need to ignore the first 7 lines which is the summery presented by top.

The bash scrip is registered on /bin, /usr/bin and /usr/local/bin.

When checking http://localhost:9091/metrics, which is supposed to show me the information gathered, I'm getting this some of information when running the scrip using shell:

cpu_usage{instance="machine",job="top",pid="114468",process="php-fpm74"} 17.6
cpu_usage{instance="machine",job="top",pid="114483",process="php-fpm74"} 11.8
cpu_usage{instance="machine",job="top",pid="126305",process="ffmpeg"} 64.7

And this is the same information when cron is running the same script:

cpu_usage{instance="machine",job="top",pid="114483",process="php-fpm+"} 5
cpu_usage{instance="machine",job="top",pid="126305",process="ffmpeg"} 60
cpu_usage{instance="machine",job="top",pid="128777",process="php"} 15

So, for some reason, when I run it from cron it cuts the process name after 7 places. I initially though it was related to the FNR>7 but even after changing it to 8 or 9 (and using exec bash to re-register the command) it gives the same results, also when I run it manually it works just fine.

Any help would be appreciated!!

0 Answers
Related