Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Include path (pwd) in bash history command

Tags:

bash

terminal

I think it would be useful to show where the command was executed when running the history command on terminal. I was able to include the datetime using:

$ echo 'export HISTTIMEFORMAT="%d/%m/%y %T "' >> ~/.bash_profile
$ source ~/.bash_profile

I tried using HISTTIMEFORMAT="${pwd} - %d/%m/%y %T " but it didn't work. I believe it only expects time syntax. How can I achieve this?

like image 944
guizo Avatar asked Feb 03 '26 10:02

guizo


1 Answers

I tried using HISTTIMEFORMAT="${pwd} ..." but it didn't work.

This is because HISTTIMEFORMAT only controls how the history command displays dates, and not how dates are stored. Inside the file .bash_history, the dates are always stored in Unix time. history loads this information and formats it using HISTTIMEFORMAT. Since the loaded information never contained the working directory, there is no chance to print it later. Therefore, we have to modify the history when it is updated.

I don't think the additional information can be reliable stored like the timestamps without modifying bash's source code. I tried it for hours.

You could add additional history entries using PROMPT_COMMAND='history -v "cd $(printf %q "$PWD")"' or you could decorate the existing entries with a comment # ran in .... I tried both, but found it very annoying, as you have to deal with the additional/modified history entries in your terminal session.

Therefore, keeping an additional history file seems to be the better option. For some examples on how to do this, see

  • How to log all Bash commands by all users on a server?
  • How can I fully log all bash scripts actions?
  • How can you log every command typed

With most solutions, you just have to add a $(pwd) somewhere in the logged string, so that the working directory is logged to.

like image 189
Socowi Avatar answered Feb 05 '26 05:02

Socowi



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!