Shell – ps output with iso date format

datepsshell

I'd like to sort this output by lstart (start of process):

ps -eo lstart,pid,cmd 

Is there a way to output lstart in ISO format like YYYY-MM-DD HH:MM:SS?

But sorting alone does not solve it. I really would like to have ISO date format.

Best Answer

Is there a way to output lstart in ISO format like YYYY-MM-DD HH:MM:SS?

With awk + date cooperation:

ps -eo lstart,pid,cmd --sort=start_time | awk '{ 
       cmd="date -d\""$1 FS $2 FS $3 FS $4 FS $5"\" +\047%Y-%m-%d %H:%M:%S\047"; 
       cmd | getline d; close(cmd); $1=$2=$3=$4=$5=""; printf "%s\n",d$0 }'

Alternative approach using ps etimes keyword(elapsed time since the process was started, in seconds):

ps -eo etimes,pid,cmd --sort=etimes | awk '{ 
       cmd="date -d -"$1"seconds +\047%Y-%m-%d %H:%M:%S\047"; 
       cmd | getline d; close(cmd); $1=""; printf "%s\n",d$0 }' 
  • date -d -"$1"seconds - difference between the current timestamp and elapsed time, will give the timestamp value of the process
Related Question