How to Get the Start Time of the Last Job in Bash

The aim of this page📝 is to explain extracting process information and start timestamps in bash based on the particular example of using jobs and ps commands.

Pavol Kutaj

--

  • The jobs command lists the current jobs in the shell, including job IDs and statuses, but does not include the start timestamp.
  • The ps command displays information about processes, such as process IDs (PIDs) and start times. However, it cannot directly take job IDs as input to print the start timestamp.
  • Using ps -p {{PID}} -o lstart retrieves the start timestamp of a process with a specific PID.
  • Extracting the PID from the jobs command output can be done using awk or cut.
  • awk '{print $2}' extracts the second field from each line of input.
  • cut -d' ' -f2 extracts the second field based on a delimiter — you could do that as an alternative. I am finding awk more elegant here.
  • The function get_job_start_time() parses jobs -l, extracts the PID, and retrieves the start timestamp.

CODE

get_last_job_start() {
# prints the start time of the last background job (no matter what status)
local last_job
local pid
last_job=$(jobs -l | tail -n 1)
if [ -n "$last_job" ]; then
pid=$(echo "$last_job" | awk '{print $2}')
if [ -n "$pid" ]; then
ps -p "$pid" -o lstart
else
echo "Failed to extract job ID"
fi
else
echo "No background jobs found"
fi
}

--

--

Pavol Kutaj

Today I Learnt | Infrastructure Support Engineer at snowplow.io with a passion for cloud infrastructure/terraform/python/docs. More at https://pavol.kutaj.com