Linux – How to change time format to seconds in ps -p

bashcentos6linuxps

I wrote a rsync script which also checks for how long the process of the script has been running.

This is the relevant part:

time=$(ps -p $processid -o etime= | awk -F: '{print $2}') # number of seconds the process is running.

if [ $(ps -ef | grep $(basename $0) &>/dev/null && echo $?) -eq "0" ] && [ "$time" -gt "5" ]; then # Check if there's a running process with the script name which is running for more than 5 seconds.
        echo "$message"
        print_log $message
        print_log "--------- END --------"
        exit 1
fi

Sometimes the process gets stuck and runs for more than 5 seconds (and even days) so the above part of the script is supposed to write it to the log.

When running:

ps -p PID -o etime=

It returns how long the process has been running.
Example:

43:36

But if the process has been running for more than a day, then the output looks like so:

[root@do01 ~]# ps -p 28518 -o etime=
 7-22:43:36

My question is how can I get this number in seconds?
because I need to make sure the process has not been running for more than 5 seconds.

Best Answer

You can try something like:

time=$(ps -p $processid -o etime= | tr -d ' ');
time_in_seconds=$(case ${#time} in "8") echo ${time: -2}+${time: -5:2}*60+${time: -8:2}*3600 | bc;;  "5")  echo ${time: -2}+${time: -5:2}*60 | bc;; *) echo $(echo $time | cut -d'-' -f1)*86400+${time: -2}+${time: -5:2}*60+${time: -8:2}*3600 | bc;; esac)
echo $time_in_seconds

Newer versions have etimes option which returns time in seconds.