On Linux, you can display the execution duration of a command while it is running using several methods. Here are the most practical approaches:
time with PROMPT_COMMAND (Bash)You can configure your shell to show the duration of each command as it runs by modifying your ~/.bashrc or ~/.bash_profile:
bash# Add to ~/.bashrc or ~/.bash_profile PROMPT_COMMAND='if [ "$(declare -p CMD_START)" ]; then echo "Duration: $((SECONDS - CMD_START))s"; unset CMD_START; fi' trap 'CMD_START=$SECONDS' DEBUG
How it works:
DEBUG trap sets CMD_START before each command.PROMPT_COMMAND calculates and displays the duration after each command.Drawback: It shows the duration after the command finishes, not during.
date in a Loop (Simple)If you want to see the duration as the command is running, you can use a loop with date:
bashstart=$(date +%s) while true; do sleep 1 duration=$(( $(date +%s) - start )) echo -ne "Elapsed time: $duration seconds\r" done
Run this in a separate terminal or background it, then run your command in another terminal.
expect to Wrap CommandsYou can use expect to wrap your command and print the duration:
bash#!/usr/bin/expect -f set start [clock seconds] spawn your_command_here expect eof set end [clock seconds] puts "Duration: [expr $end - $start]s"
Save as run_with_duration.sh, make it executable, and run it.
script CommandIf you want to log everything, including the duration:
bashscript -q -c "your_command_here" /dev/null
The duration is not shown in real-time, but you can calculate it afterward.
time Command (Post-Execution)The simplest way to see the duration after the command finishes:
bashtime your_command_here
This will output something like:
textreal 0m1.003s user 0m0.001s sys 0m0.002s
tput for Real-Time UpdatesIf you want a real-time counter in the terminal, you can use a script like this:
bash#!/bin/bash start=$(date +%s) your_command_here & pid=$! while kill -0 $pid 2>/dev/null; do duration=$(( $(date +%s) - start )) echo -ne "Elapsed time: $duration seconds\r" sleep 1 done echo -e "\nCommand finished after $duration seconds"
Which method do you prefer or need help setting up?
Vibe can make mistakes. Check answers. Learn more