2

I'm pretty new to linux scripting but I'm trying to create this script to add into the crontab in order to check if a user process has been running for more than x amount of time.

#! /bin/sh
#This feeds the list of process over 1 hour and strips the colons and sees 
#if it is over 12 hours. If so, then mails it to me.
if $(( (ps exo time,pid | grep -v "00:00:" | awk '{print $1}' | sed s/://g) >= 001200 )); then
    mailx -s "$(hostname) Long Process Detection" me@example.com
fi

As of right now, it's producing an error that it is missing a ')', but I've looked it over many times and I can't see any unclosed parenthesis. Any help on this would be appreciated. The error reads

"missing ')' (error token is "exo time,pid |grep -v "00:00:" | awk '{print }' | sed s/://g) >= 001200 ")"

The above is solved with shifting the $ inside the opened parenthesis, but it's feeding back an error at the conditional calculation. (i.e. 000106 >= 000010 in my sample).

JCrowder
  • 23
  • 5
  • Difficult to say if there is an error in the script or the copy paste, but the if clause gets a missing ")". 3 open, 2 close. – Andre Gelinas Oct 22 '18 at 19:12
  • ah, that was an error in my versions. that came from a notepad vs the server. I have 3 closing on the server where I am getting the error. – JCrowder Oct 22 '18 at 19:19
  • What should the contents of the email be? Do you want the if condition to be true if there is *any* process that's been running longer than 12 hours? – Benjamin W. Oct 22 '18 at 19:49
  • Preferrably user processes, not root. But I was just trying to get it to resolve for any process before I fixed that. Your solution earlier fixed the missing ), but it's having an issue calculating the numeric values. (i.e. 000106 >= 000010 is my sample). The mail body would just include the process user id, process id, and the time. – JCrowder Oct 22 '18 at 19:51
  • See this post: [How to use double or single brackets, parentheses, curly braces](https://stackoverflow.com/q/2188199/6862601). – codeforester Oct 22 '18 at 19:52

1 Answers1

0

Actually, not sure about your code but this should do want you want I hope :

#!/bin/sh
#This feeds the list of process over 1 hour and strips the colons and sees
#if it is over 12 hours. If so, then mails it to me.
for i in $(ps exo time,pid | grep -v "00:00:" | grep -v "TIME" | awk '{print $1}' | sed 's/://g');do
    if [ $i -ge 001200 ]; then
            #echo $i
            mailx -s "$(hostname) Long Process Detection" me@example.com
    fi
done

Just play with the comment to either do your mailing or test the values found.

Andre Gelinas
  • 912
  • 1
  • 8
  • 10
  • Given that `awk` can do anything `grep` and `sed` can do, the sequence `grep ... | grep ... | awk ... | sed ...` is rather ugly ;-) – Mark Setchell Oct 22 '18 at 23:16