How to get time before launching a command each time in terminal?

I would like that each time I run a command in terminal I have the time displayed in my term then the command executed.


You can just run

 PROMPT_COMMAND="date"

on your terminal then every time a command is ran on your terminal the current date and time will be printed out on your terminal. As suggested by@pa4080, to make it permanent, add PROMPT_COMMAND="date" to your ~/.bashrc file.

From man bash:

PROMPT_COMMAND

If set, the value is executed as a command prior to issuing each primary prompt.

I think you can use the same command PROMPT_COMMAND= to run almost "anything" you want to run when a command is ran on the terminal.

If you use tmux, it also display time on the corner:

tmux


Assuming you're running Bash, you can set PROMPT_COMMAND to a command that is executed when the prompt is printed out. Similarly, you could run an arbitrary command by including a command substitution in the prompt:

$ PS1='[$(date +"%T")] \u@\h \w\$ '
[22:17:54] user@somehost /tmp$ 

But this is common enough that Bash supports it off the shelf

\D{format}
The format is passed to strftime(3) and the result is inserted into the prompt string; an empty format results in a locale-specific time representation. The braces are required.

So, similarly to the previous

$ PS1='[\D{%T}] \u@\h \w\$ '

But those print the time the prompt was printed. This may be quite a while before the next command is executed. To get the time the command is started, we can use the DEBUG trap, which runs once for each command line executed.

$ starttime() { date +"Command started at %T"; }
$ trap starttime DEBUG
$ ls -l /dev/null
Command started at 22:25:07
crw-rw-rw- 1 root root 1, 3 Jul 18 21:46 /dev/null

The DEBUG trap could also use the $BASH_COMMAND variable which contains the command being executed, but that's probably not very useful since the command line is visible at the prompt anyway.


use zsh terminal, this terminal can show date time run commandenter image description here

https://github.com/robbyrussell/oh-my-zsh/wiki/themes#rkj-repos https://github.com/robbyrussell/oh-my-zsh/wiki/themes#xiong-chiamiov