3

I'm working on an open source project to tracking the research activities. In one of the modules, I want to track the command history of a folder into the file(.history) which is the same folder.

Example:

Let's say, I'm working on a folder /Users/ravi/test-project/ . I'm using few of commands to start my work in that folder. Let's say I executed the following commands in the folder.

$wget https://mywebsite.com/script.py
$chmod +xw script.py
$echo "append some text " >  script.py 
$python script.py

I want all these commands to be saved into .history file of the folder ie., /Users/ravi/test-project/.history.

Help much appreciated. Thanks in advance.

rrmerugu
  • 1,826
  • 2
  • 20
  • 26
  • See http://stackoverflow.com/questions/3360738/execute-a-bash-function-upon-entering-a-directory for how to execute a command whenever you change directories. You can use this to change `$HISTFILE`. – Barmar Jul 09 '16 at 14:27
  • On Changing directory method looks interesting, my only concern is whether that will work if a user does "open terminal here" from the right click menu. I will dig deep into it thanks. – rrmerugu Jul 09 '16 at 14:36
  • I don't see why it shouldn't work. It runs the function every time it displays a shell prompt. – Barmar Jul 09 '16 at 14:38
  • Also regarding `$HISTFILE`. I tried `export HISTFILE=$PWD/.bash_history` in the folder. but its not creating the file .bash_history or saving the history. Any thoughts @Barmar – rrmerugu Jul 09 '16 at 14:38
  • By default it doesn't save history until the shell exits. At that time it will use the current value of `HISTFILE`. See http://askubuntu.com/questions/67283/is-it-possible-to-make-writing-to-bash-history-immediate for how to make it save after every command. – Barmar Jul 09 '16 at 14:42

1 Answers1

4

This was actually pretty easy:

PROMPT_COMMAND="history -a; history -c; history -r; HISTFILE=\${PWD}/.history"

This first ensures that history is written and then re-read on every prompt*. Then it changes the history file variable to use the current directory. Example session:

$ echo "$PWD"
/home/username
$ cd /tmp
$ echo "$PWD"
/tmp
$ cat ~/.history 
echo "$PWD"
cd /tmp
$ cat .history
echo "$PWD"

As you can see, the cd command is stored in the history file of the directory the command was executed in, and the echo commands are stored in both history files.

One side effect to note is that history is now shared between every terminal. I love this feature, but not everyone does.

Also, if you're looking for auditing rather than convenience of history you should probably look into enabling auditd or something similar.

* Don't worry, it's super fast even with thousands of lines of history.

l0b0
  • 55,365
  • 30
  • 138
  • 223