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.
2 min readMar 29, 2024
- The
jobscommand lists the current jobs in the shell, including job IDs and statuses, but does not include the start timestamp. - The
pscommand 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 lstartretrieves the start timestamp of a process with a specific PID. - Extracting the PID from the
jobscommand output can be done usingawkorcut. awk '{print $2}'extracts the second field from each line of input.cut -d' ' -f2extracts 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()parsesjobs -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
}