How to View the Execution Time of Every Bash Command by Modifying the PS1 Prompt

When running scripts, compiling code, or downloading large files in the Linux terminal, knowing exactly how long a specific task took to complete is vital for benchmarking and optimization. The traditional method for this is to prepend the time command before your execution (e.g., time ./myscript.sh).

However, this requires you to remember to type time before you hit Enter. If you run a command and it ends up taking five minutes, you cannot retroactively find out the exact execution time. A far more elegant solution for power users is to dynamically embed a stopwatch directly into your bash prompt, ensuring every single command you ever run is automatically timed.

The Logic Behind the Hack

We can achieve this by tapping into a hidden bash variable called $SECONDS. This built-in variable tracks the number of seconds the current shell has been running. By capturing the value of $SECONDS right before a command executes, and comparing it to the value right after it finishes, we can calculate the exact duration of the command.

Modifying Your .bashrc

To implement this, we need to modify two bash features: trap DEBUG (which runs right before a command executes) and PROMPT_COMMAND (which runs right before the prompt is redrawn after a command finishes).

  1. Open your terminal.
  2. Open your bash configuration file in a text editor (like nano):
    nano ~/.bashrc
  3. Scroll to the very bottom of the file and paste the following block of code:
    # Start the timer before command execution
    trap 'timer_start=${timer_start:-$SECONDS}' DEBUG
    
    # Calculate time and format the prompt
    set_prompt() {
        local timer_show=$(($SECONDS - $timer_start))
        
        # Only show the timer if the command took longer than 0 seconds
        if [[ $timer_show -gt 0 ]]; then
            local timer_string="[${timer_show}s] "
        else
            local timer_string=""
        fi
        
        # Set the actual PS1 prompt. (This is a basic green prompt)
        PS1="${timer_string}\[\033[01;32m\]\u@\h\[\033[00m\]:\[\033[01;34m\]\w\[\033[00m\]\$ "
        
        unset timer_start
    }
    
    # Run the set_prompt function before drawing the prompt
    PROMPT_COMMAND=set_prompt
  4. Save the file and exit the editor (in nano, press Ctrl+O, Enter, then Ctrl+X).
  5. Reload your configuration to apply the changes immediately:
    source ~/.bashrc

How It Looks in Practice

Now, try running a command that takes a few seconds to complete, such as sleep 3.

When the prompt returns, you will see [3s] prepended to your normal username and path. If you run a command that is instant (like ls or pwd), the timer string evaluates to zero and remains hidden, keeping your terminal interface perfectly clean during rapid-fire typing.

Get the best tech tips delivered straight to your inbox.

Join thousands of readers mastering Apple, Google, Microsoft, and Linux.