I am trying to modify my ~/.bash_profile
so that the Unix epoch time automatically gets printed before and after the execution of every issued command in bash, like so:
[prompt]$ some-maybe-multiline-command
Started execution at: <epoch time>
...
<stuff printed out by some-maybe-multiline-command, if any>
...
Finished execution at: <epoch time>
[prompt]$
How can I achieve this? Ideally, I want to have minimum side effects while doing so (e.g. I do not want this change to affect too many logs if possible); it should ideally only affect what I see on the terminal screen.
Thanks a lot in advance!
I found this answer Unix StackExchange, and tried to adopt it to my situation; but I haven't been successful so far..
Adding trap <command> DEBUG
into the ~/.bash_profile
is the closest thing to a solution that I found so far. However, I am not sure how to make the <command>
be aware of whether it is being executed before or after the execution of the issued command
You can use Bash's PS0
(requires bash 4.4+) and PROMPT_COMMAND
.
According to man bash
:
PROMPT_COMMAND
If this variable is set, and is an array, the value of each set element is executed as a command prior to issuing each primary prompt. If this is set but not an array variable, its value is used as a command to execute instead.
PS0
The value of this parameter is expanded and displayed by interactive shells after reading a command and before the command is executed.
Example:
PS0='>>> $( date +%s )\n'
PROMPT_COMMAND='echo "<<< $( date +%s )"'
$ echo hello world; sleep 2
>>> 1686801897
hello world
<<< 1686801899