On Linux how to display the command execution duration while it is running?
Mar 28, 10:03pm

On Linux, you can display the execution duration of a command while it is running using several methods. Here are the most practical approaches:


1. Using 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:

  • The 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.


2. Using date in a Loop (Simple)

If you want to see the duration as the command is running, you can use a loop with date:

bash
start=$(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.


3. Using expect to Wrap Commands

You 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.


4. Using script Command

If you want to log everything, including the duration:

bash
script -q -c "your_command_here" /dev/null

The duration is not shown in real-time, but you can calculate it afterward.


5. Using time Command (Post-Execution)

The simplest way to see the duration after the command finishes:

bash
time your_command_here

This will output something like:

text
real    0m1.003s
user    0m0.001s
sys     0m0.002s

6. Using tput for Real-Time Updates

If 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?

Mar 28, 10:03pm

This is a shared conversation and may include unverified content that doesn't reflect Mistral AI's views. Login to resume chatting.

Vibe can make mistakes. Check answers. Learn more