DEV Community

chinmay chhajed
chinmay chhajed

Posted on • Updated on

Add time stamp in your shell prompt

Bash prompt can be set by setting the environment variable PS1. We need to update this variable to get time in our prompt.

There are 4 ways to get the time in prompt. If you see manual page for bash, you can see time can be set using:

\t     the current time in 24-hour HH:MM:SS format
\T     the current time in 12-hour HH:MM:SS format
\@     the current time in 12-hour am/pm format
\A     the current time in 24-hour HH:MM format
Enter fullscreen mode Exit fullscreen mode

Note that the time is not the current time but the time when prompt was last updated. Prompt will be updated when previous command completed.

Sample usage:

PS1="\t $ "   # 11:13:54 $ 
PS1="\T $ "   # 11:14:01 $ 
PS1="\@ $ "   # 11:14 AM $ 
PS1="\A $ "   # 11:14 $ 
Enter fullscreen mode Exit fullscreen mode

Add whichever style you like to your $HOME/.bashrc and every time you open a new terminal, you will see time in command prompt.

If you wish to show current directory with time in prompt, a nice prompt setting could be like

PS1="\w \A $ "
PROMPT_DIRTRIM=2
# Resulting in prompt to look like
# ~/.../bluetooth/nimble 11:16 $ 
Enter fullscreen mode Exit fullscreen mode

Here PROMPT_DIRTRIM would set the number of parent directories you wish to see in the prompt.

Checkout designing a minimal bash prompt.

Top comments (0)