Tonight I tried to write a POSIX shell script which would allow me to check how long a process is running (via it's ID) and be able to handle multiple inputs:
#!/bin/sh
is_this_a_number()
{
if [ "$1" -eq "$1" ] 2> /dev/null
then
return 0
else
return 1
fi
}
does_pid_exist()
{
if ps --pid "$1" > /dev/null 2>&1
then
return 0
else
return 1
fi
}
how_long_pid_has_been_running()
{
ps --pid "$1" --format etime=
}
trim_leading_and_trailing_spaces()
{
awk '{$1=$1;print}'
}
arg_pos=0
while [ "$#" -gt 0 ]
do
arg_val="$1"
arg_pos=$((arg_pos + 1))
if ! is_this_a_number "$arg_val"
then
echo "The argument at position $arg_pos is not a number."
else
echo "Process ID $arg_val"
if ! does_pid_exist "$arg_val"
then
echo "This process does not exist."
else
how_long_pid_has_been_running "$arg_val" | trim_leading_and_trailing_spaces
fi
fi
printf "\\n"
shift
done
Usage:
./how-long-pid-is-running 1 10078 c 40545454
Where 10078 is an instance of Chrome.
The output is as follows:
Process ID 1
09:04:31
Process ID 10078
07:32:32
The argument at position 3 is not a number.
Process ID 40545454
This process does not exist.