0

I am aware that it is possible to add timestamps to bash_history.

The examples I've seen so far it always uses the current system time. And here is the problem for me: On the one hand, I like to keep logs in UTC because it makes it way easier to correlate stuff. On the other hand I'm working in a non-UTC timezone so my system time is not set to UTC.

Is there a way to have your system set to e.g., UTC+1 but still log bash_history using the UTC time?


Okay so based on the answer by @meuh I found a way to achieve what I was looking for:

  1. Set HISTTIMEFORMAT as you like. It only controls formatting (duh!). I chose: HISTTIMEFORMAT='%F %T %z '
  2. To display the history in UTC on a system in another timezone, set the TZ variable to UTC for that command only:
$TZ='UTC' history
....
 1040  2023-05-27 12:30:02 +0000 cat ~/.bashrc 
 1041  2023-05-27 12:30:11 +0000 grep -i hist ~/.bashrc
 1042  2023-05-27 12:36:21 +0000 TZ='UTC' history

Run history without setting TZ and you get the time presented in your current TZ (compare the numeric timezone in the output to previous one):

$ history
... 
1040  2023-05-27 14:30:02 +0200 cat ~/.bashrc 
1041  2023-05-27 14:30:11 +0200 grep -i hist ~/.bashrc
1042  2023-05-27 14:36:21 +0200 TZ='UTC' history
John Nemo
  • 17
  • 3

1 Answers1

2

You do not need to anything at all, because timestamps in the history file are always saved in seconds since the Unix epoch. It is only when you print them that they are converted to whatever timezone you are in. You should be able to see this by comparing the output of date +%s with the number in the history file (save to the file with history -w). Or use HISTTIMEFORMAT='%s: ' to see this number instead of whatever converted date format you are currently seeing. The number will not change if you change timezone, eg:

$ TZ=UTC date +'%s %H:%M'; TZ=CET date +'%s %H:%M'
1684429600 17:06
1684429600 19:06
meuh
  • 1,563
  • 10
  • 11
  • Agreed, it's not ideal, but the best you can do is use %s to get epoch-seconds. Then use https://serverfault.com/questions/631216/replace-date-in-epoch-seconds-format-to-normal-in-a-log-file to view. – pjz May 18 '23 at 19:21
  • Okay so based on this answer by @meuh I found a way to achieve what I was looking for: 1. Set HISTTIMEFORMAT as you like. It only controls formatting. I chose: `HISTTIMEFORMAT='%F %T %z '` 2. To **display** the history in UTC on a system in another timezone, set the TZ variable to UTC for that command only: ``` $TZ='UTC' history .... 1040 2023-05-27 12:30:02 +0000 cat ~/.bashrc 1041 2023-05-27 12:30:11 +0000 grep -i hist ~/.bashrc 1042 2023-05-27 12:36:21 +0000 TZ='UTC' history ``` Run history without setting TZ and you get the time presented in your current TZ. – John Nemo May 27 '23 at 12:34