Sometimes it would be useful to look back a command I know I used for a specific bit of analysis, but maybe I don't recall the exact file path where the files for the analyses (or whatever) were.

Does anyone know of any 3rd party tools or work arounds whereby the command history could be stored, along with the working directory at the time of invocation?

2 Answers 2


Bash has two features that might be helpful if you're willing to do some minor scripting.

  1. Bash variable PROMPT_COMMAND will execute a command or function after every command finishes.

  2. Bash trap DEBUG will execute a bash function before every command begins.

You could script for either of those features a function to output to a file of your choice the current directory $PWD and the command string $BASH_COMMAND.

  • Ah this could be what I'm looking for.. I could write my own history file with the $PWD appended to it. Do you know how exactly bash captures the command that was executed in the history normally?
    – Joe Healey
    Commented Jan 17, 2018 at 11:46

A limited-case work-around would be to add the current directory to your $PS1. That would be helpful in the limited cases of: 1) using a terminal emulator running in an X11 window that has scroll-back; 2) using any terminal emulator or even a raw console, but with tmux or other such program that provides its own scroll-back.

Note that tmux does provide a command to search through your scroll-back, which would help you find specific commands. Some terminal emulators may also have search functions.

The major drawback would be that the scroll-backs would contain all your STDOUT and STDERR in addition to your STDIN.

Finally, tmux has a plug-in called tmux-logging that can save all your session to a file.

  • I already do have my working directory in my $PS1, but this isn't saved with the history. tmux may be the way to go, I get sick of losing my history with screen too...
    – Joe Healey
    Commented Jan 17, 2018 at 11:10

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .